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"}}
Adam Matan
  • 128,757
  • 147
  • 397
  • 562
  • 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). – Felix Kling Mar 27 '12 at 15:17
  • This is a printing problem, not a parsing problem. – Matt Ball Mar 27 '12 at 15:17
  • Reminds me of the old infomercials...: "Sorry, Tennessee." – lance Mar 27 '12 at 15:17
  • 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()` http://api.jquery.com/jQuery.getJSON/ – Dutchie432 Mar 27 '12 at 15:20
  • I believe you can use the method suggested [here](http://stackoverflow.com/a/4992429/537913) for flattening your object – J. Ed Mar 27 '12 at 15:18

2 Answers2

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/

millimoose
  • 39,073
  • 9
  • 82
  • 134
2

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

smcg
  • 3,195
  • 2
  • 30
  • 40