Reputation: 187
I have this json file called gameupdater.json
gameupdater.json:
{ "730":{
"success":true,
"data":{
"price_overview":{
"currency":"EUR",
"initial":1399,
"final":937,
"discount_percent":33
}
}
}
}
And I have a javascript file that has the following code:
var updater = JSON.parse(fs.readFileSync('gameupdater.json'));
var jsonstring = JSON.stringify(updater, null, 4);
var num = updater.730.data.priceoverview.initial;
console.log(num);
Yet whenever I run it (node bot.js) in CMD. It does not give me what I am looking for, which is 1399.
It instead gives me this error:
var num = updater.730.data.priceoverview.initial;
^^^^
SyntaxError: Unexpected number
Oh, I'm pretty sure it would be hard to change stuff, since this array is going to be automatically downloaded from this website: http://store.steampowered.com/api/appdetails?appids=730
Upvotes: 0
Views: 72
Reputation: 45736
You can't use a number with the dot syntax. You need to use the brace syntax, and access it as a string:
updater["730"].data...
Or, if the property is entirely a number, you can also use a bare number, but again, it must be inside the square braces:
updater[730].data...
Upvotes: 3
Reputation: 42352
You can't use dot operator to access properties of an object if it starts with a number - you must use the bracket notation[]
.
See the Dot Notation section in this MDN link - Property Accessors
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
See demo below:
var updater = {
"730": {
"success": true,
"data": {
"price_overview": {
"currency": "EUR",
"initial": 1399,
"final": 937,
"discount_percent": 33
}
}
}
};
var jsonstring = JSON.stringify(updater, null, 4);
var num = updater['730'].data.price_overview.initial;
console.log(num);
Upvotes: 2