0

This is my JSON: (This is AJAX response data)

{"id":"1","code":"43","doc":"{\"date\":\"2016\",\"name\":\"NAME1\",\"id\":\"7\"}"}

I would like to parse this JSON with jQuery:

var obj = jQuery.parseJSON(data);

This is doc: console.log(obj.doc);

{\"date\":\"2016\",\"name\":\"NAME1\",\"id\":\"7\"}

But how do I refer to the "name"? I do not refer to obj.doc.name, because the "name" is not element on the object.

3
  • 1
    You can clearly see that the the value of obj.doc is a string containing JSON. You'd need to apply JSON.parse(obj.doc) again. Better however would be to fix the code that generates the JSON to not double encode your data. Commented Feb 23, 2017 at 22:32
  • It appears as though doc is itself JSON, so you'll need to parse it. Something like var obj = jQuery.parseJSON(data); obj.doc = jQuery.parseJSON(obj.doc); Commented Feb 23, 2017 at 22:32
  • 1
    THX! This is working! Commented Feb 23, 2017 at 22:38

2 Answers 2

2

Since the value of the "doc" attribute in your object is a string, you will need to parse that value to treat it as a JSON object.

After the first parse you could do:

var doc = JSON.parse(obj.doc)

Then you can access doc.name.

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

Comments

1

In this case response is already JSON. You want parse data.doc only.

You can do this like that:

data.doc = jQuery.parseJSON(data.doc)

and now when you get what you wanted.

> console.log(data.doc.name)
NAME1

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.