0

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.

1 Answer 1

2

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!

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

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.