Reputation: 2352
I'm reading a JSON file and parsing it with NodeJS, the JSON file looks like this:
{
"id": 5,
"x": 9.996,
"y": 0.135,
"v": {
"x1": 0.653,
"y1": -0.064
},
"z": 1.4730991609821347
}, {
...
}
So I can easily put that into a variable, JSON.parse()
it and access it without any problems:
var parsed = JSON.parse(jsonVar)
console.log(parsed.id) // prints 5
The problem comes when I try to access x1
or y1
from parsed.v
. It comes out with an object and it behaves really weird.
I have tried:
parsed.v.x1 // gave me an error, x1 doesn't exist
also
var string = JSON.stringify(parsed.v) // returns {"x":0.653,"y":-0.064}
Trying to parse the above and access it also gives me an error
var parsedNew = JSON.parse(string)
console.log(parsedNew.x) //error
Am I missing something there? Running out of ideas really.
Upvotes: 0
Views: 62
Reputation: 9084
Actually, there is no need to parse or do anything to access the data, as it already is a javascript object, try something like this:
var json = {
"id": 5,
"x": 9.996,
"y": 0.135,
"v": {
"x1": 0.653,
"y1": -0.064
},
"z": 1.4730991609821347
};
console.log(json.v.x1); // this will output '0.653'
And by the way, JSON.stringify()
just converts the input into a String
, so it is not really what you need.
Hope this helps!
Upvotes: 2