1

I have a JSON response as follows in the form of [object Object] under variable data :

{
    "name": "John Johnson",
    "street": "Oslo West 16",
    "posts": {
        "id1": "121331",
        "id2": "9089085",
        "id3": "3424234"
    }
}

data equals [object Object] and

data.posts equals {"id1":"121331","id2":"9089085","id3":"3424234"}

How to simply access id3 value because it does not equal data.posts.id3 nor equals data.posts['id3'] ?

JSON.stringify(data) gives \n and \ between the objects inside posts Only? could this be the problem?:

{
    "name": "John Johnson",
    "street": "Oslo West 16",
    "posts": { \n \"id1\": \"121331\", \n \"id2\": \"9089085\", \n \"id3\": \"3424234\"
    }
}
8
  • Why do you say it does not equal those expressions? Which error are you finding? Commented Feb 11, 2016 at 0:52
  • This is what I'm getting when I alert them they are undefined, I'm working in angularjs environment Commented Feb 11, 2016 at 0:53
  • Also when I JSON.stringify(data) it gives me the object array with multiple back slash n \n in between the objects... Is this normal? Commented Feb 11, 2016 at 0:56
  • I suspect data.posts is actually a string. What does JSON.parse(data.posts).id3 give you? Commented Feb 11, 2016 at 1:13
  • 1
    How are you creating this JSON on the server? Just in case you are, you should never generate it "by hand" but always use native functions or libraries (e.g. in the case of PHP - json_encode) to generate the JSON for you. Otherwise you could end up with a problem similar to what you are seeing here. Commented Feb 11, 2016 at 1:18

1 Answer 1

2

I suspect data.posts is actually a string. Try

JSON.parse(data.posts).id3

You should probably figure out why data.posts is a string though, because doing JSON.parse(data.posts) every time you need to get something from data.posts is not very efficient, not to mention the extra overhead of double JSON-encoding.

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.