Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Javascript: How to generate formatted easy-to-read JSON straight from an object? [duplicate]

Possible Duplicate:
How can I beautify JSON programmatically?

I know how to generate JSON from an object using JSON.stringify, or in my case the handy jquery-json from google code (https://github.com/krinkle/jquery-json).

Now this works fine, but the output is hard to read for humans. Is there an easy way / function / whatever to output a neatly formatted json file?

This is what I mean:

JSON.stringify({a:1,b:2,c:{d:1,e:[1,2]}});  

gives..

"{"a":1,"b":2,"c":{"d":1,"e":[1,2]}}" 

I'd like something like this instead:

{  "a":1,  "b":2,  "c":{     "d":1,     "e":[1,2]  } } 

E.g. with newlines and tabs added. It's much easier to read for larger documents.

I'd like to do this ideally without adding any huge libraries - e.g. not prototype or YUI or whatever.

like image 606
Ben Clayton Avatar asked Aug 18 '10 18:08

Ben Clayton


People also ask

How do I auto format a JSON file?

The key-map to auto-format the selected JSON is ALT-SHIFT-F. This is the same key-map to auto-format other languages too, so I often find myself doing CTRL-A (for select all text) followed by ALT-SHIFT-F to fix my messy C# code after a series of cut and paste operations.

How do I beautify a JSON string?

Use JSON. stringify(obj) method to convert JavaScript objects into strings and display it. Use JSON. stringify(obj, replacer, space) method to convert JavaScript objects into strings in pretty format.

What is JSON Stringify?

The JSON. stringify() method converts a JavaScript object or value to a JSON string, optionally replacing values if a replacer function is specified or optionally including only the specified properties if a replacer array is specified.

What does toJSON do in JavaScript?

The toJSON() function is an important tool when building classes in JavaScript. It is how you control how JavaScript serializes your class into JSON. The toJSON() function can help you solve numerous problems, like making sure dates or Node. js buffers get serialized in the right format for your app.


1 Answers

JSON.stringify takes more optional arguments.

Try:

 JSON.stringify({a:1,b:2,c:{d:1,e:[1,2]}}, null, 4); // Indented 4 spaces  JSON.stringify({a:1,b:2,c:{d:1,e:[1,2]}}, null, "\t"); // Indented with tab 

From:

How can I beautify JSON programmatically?

Should work in modern browsers, and it is included in json2.js if you need a fallback for browsers that don't support the JSON helper functions. For display purposes, put the output in a <pre> tag to get newlines to show.

like image 87
Cristian Sanchez Avatar answered Oct 14 '22 07:10

Cristian Sanchez