sridattas
sridattas

Reputation: 509

How to parse JSON with key as number, returns undefined?

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

Upvotes: 1

Views: 558

Answers (3)

Matt Ellen
Matt Ellen

Reputation: 11592

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']);

Upvotes: 2

flyingpluto7
flyingpluto7

Reputation: 1099

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

Upvotes: 1

gaaaaaa
gaaaaaa

Reputation: 366

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.

Upvotes: 0

Related Questions