1

I'm trying to read the data from my json with below format but it results with undefined

My JSON as below

{
    "1": "A",
    "2": "B",
    "3": "C",
    "4": "D",
    "5": "E",
    "6": "F",
    "key":"pair"    
}

I'm parsing as below

rawdata = fs.readFileSync('data.json');
data = JSON.parse(rawdata);
console.log(data.1) //returns undefined. I tried parsing 1 to String but resulted same.
console.log(data.key) //returns pair
2
  • You can use [] notation to get values in an object like data["1"] Commented May 21, 2020 at 13:00
  • @Srinu I tried with bracket notation as mentioned but it returned 'undefined' Commented May 22, 2020 at 4:25

3 Answers 3

2

You can't use dot notation to access an object's property if that property's name starts with a number.

To get a the property you'll need to use square bracket notation:

let o = JSON.parse(`{
    "1": "A",
    "2": "B",
    "3": "C",
    "4": "D",
    "5": "E",
    "6": "F",
    "key":"pair"    
}`);

console.log(o['1']);

Sign up to request clarification or add additional context in comments.

Comments

1

In case of dot notation to access a value, the property key must be a valid identifier

In this code, property must be a valid JavaScript identifier, i.e. a sequence of alphanumerical characters, also including the underscore ("_") and dollar sign ("$"), that cannot start with a number. For example, object.$1 is valid, while object.1 is not.

You can use bracket notation in this case

obj['1']

Spec: Property Accessors

Comments

0

You can try using rawdata = fs.readFileSync('./data.json'); This tells the script the data.json file is in the same folder as it. And then use .data['1'] to get the value.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.