20

Possible Duplicate:
JSON pretty print using JavaScript

I'm working on a project that will be used to help analyse and understand JSON arrays by future developers of a platform. I'm referencing Facebook's brilliant Graph Explorer page, seen here, and want to output our array in a prettified, correctly tab indented and line breaker array, just as it does on the explorer.

The arrays are outputted to a textarea, and because of this I think I'm running into issues with the line breaking and tabbing. I've also tried using the prettify library, but with no luck.

Example:

{"outcome" : "success", "result" : {"name" : "messaging-sockets", "default-interface" : "external", "include" : [], "socket-binding" : {"messaging" : {"name" : "messaging", "interface" : null, "port" : 5445, "fixed-port" : null, "multicast-address" : null, "multicast-port" : null}, "messaging-throughput" : {"name" : "messaging-throughput", "interface" : null, "port" : 5455, "fixed-port" : null, "multicast-address" : null, "multicast-port" : null}}}, "compensating-operation" : null}

To:

{
   "outcome":"success",
   "result":{
      "name":"messaging-sockets",
      "default-interface":"external",
      "include":[

      ],
      "socket-binding":{
         "messaging":{
            "name":"messaging",
            "interface":null,
            "port":5445,
            "fixed-port":null,
            "multicast-address":null,
            "multicast-port":null
         },
         "messaging-throughput":{
            "name":"messaging-throughput",
            "interface":null,
            "port":5455,
            "fixed-port":null,
            "multicast-address":null,
            "multicast-port":null
         }
      }
   },
   "compensating-operation":null
}
Community
  • 1
  • 1
Ryan Brodie
  • 6,554
  • 8
  • 40
  • 57

1 Answers1

65

You may use JSON.stringify:

JSON.stringify(jsonobj,null,'\t')

See the demo.

UPDATE: If you don't have jsonobj,but have json string,then before using stringify function,convert json string to json object by this line:

jsonobj = JSON.parse(jsonstring);
Engineer
  • 47,849
  • 12
  • 88
  • 91
  • Not working - output is like `"{\"streamtype\":\"returnAll\"}`, as a string, with no line breaks or tabs. – Ryan Brodie Jul 06 '12 at 09:28
  • 2
    @RyanBrodie You need to pass `Object`,not a `String`, that's why you got such results. To convert string to object, use `JSON.parse(yourstring)`,and then pass to `JSON.stringify` function. So you need to do this: `JSON.stringify(JSON.parse(yourstring),null,'\t')` – Engineer Jul 06 '12 at 09:30
  • 1
    does not work for me. I try this and it's still not formatted: $("#transactionResponse").show().html(JSON.stringify(data, null, '\t')); where data is the response json in my jQuery #.ajax() callback – PositiveGuy Dec 16 '13 at 06:03
  • Thanks @Engineer! – ScanQR Feb 12 '19 at 14:42