4

Consider the following nested JSON:

{
  "state": [
    "Tennessee"
  ], 
  "more_data": [
    {
      "letters": {
        "last": "e", 
        "first": "T"
      }
    }
  ]
}

I want to print the JSON in JavaScript in a flat manner, i.e. root_key=value:

  var my_json_str = "{\"state\":[\"Tennessee\"],\"more_data\":[{\"letters\":{\"first\":\"T\",\"last\":\"e\"}}]}";
  console.log(my_json_str);
  my_json = jQuery.parseJSON(my_json_str);
  for (var key in my_json) {
      console.log(key,":",my_json[key]);
  }

But I get (FireBug console):

state : ["Tennessee"]
more_data : [Object { letters={...}}]

Instead of the desired:

state:["Tennessee"]
more_data:[{"letters":{"first":"T","last":"e"}}]

How do I fix this?

Solution - following your answers:

http://jsfiddle.net/wrAUB/

var jsonStr = "{\"state\":[\"Tennessee\"],\"more_data\":[{\"letters\":{\"first\":\"T\",\"last\":\"e\"}}]}";

var jsonObj = JSON.parse(jsonStr);
for (key in jsonObj) {
    console.log(key+':'+JSON.stringify(jsonObj[key]));
}
​

Which gives:

state:"Tennessee"
more_data:{"letters":{"first":"T","last":"e"}}
5
  • 3
    You don't have to fix anything, there is nothing wrong (well, unless you really want to print it in a different way, but why?). It's just how Firebug displays nested objects. You can work with the data as expected. Btw, you don't have JSON within JSON. You just have JSON (JSON within JSON would be something like {"foo": "{\"bar\": 42}"}, i.e. a string containing JSON). Commented Mar 27, 2012 at 15:17
  • This is a printing problem, not a parsing problem. Commented Mar 27, 2012 at 15:17
  • Reminds me of the old infomercials...: "Sorry, Tennessee." Commented Mar 27, 2012 at 15:17
  • I believe you can use the method suggested here for flattening your object Commented Mar 27, 2012 at 15:18
  • 1
    Just a side note, but if you are fetching the JSON with ajax, you can use $.getJSON() and this will eliminate the need to use $.parseJSON() api.jquery.com/jQuery.getJSON Commented Mar 27, 2012 at 15:20

2 Answers 2

5

You can use JSON.stringify to turn the objects you're iterating over back into JSON strings:

var jsonStr = "{\"state\":[\"Tennessee\"],\"more_data\":[{\"letters\":{\"first\":\"T\",\"last\":\"e\"}}]}";

​var jsonObj = JSON.parse(jsonStr);
for (key in jsonObj) {
    console.log(key+':'+JSON.stringify(jsonObj[key]));
}

See it in action on jsFiddle: http://jsfiddle.net/hEvFr/

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

Comments

2

Sounds like you would want to call JSON.stringify on the values of the key-value pairs.

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.