How can I display JSON in an easy-to-read (for human readers) format? I'm looking primarily for indentation and whitespace, with perhaps even colors / font-styles / etc.
相关问题
- Is there a limit to how many levels you can nest i
- Jackson Deserialization not calling deserialize on
- How to maintain order of key-value in DataFrame sa
- How to toggle on Order in ReactJS
- StackExchange API - Deserialize Date in JSON Respo
Better way.
Prettify JSON Array in Javascript
You can use
JSON.stringify(your object, null, 2)
The second parameter can be used as a replacer function which takes key and Val as parameters.This can be used in case you want to modify something within your JSON object.more reference : https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/JSON/stringify
If you're looking for a nice library to prettify json on a web page...
Prism.js is pretty good.
http://prismjs.com/
I found using JSON.stringify(obj, undefined, 2) to get the indentation, and then using prism to add a theme was a good approach.
If you're loading in JSON via an ajax call, then you can run one of Prism's utility methods to prettify
For example:
You can use
console.dir()
, which is a shortcut forconsole.log(util.inspect())
. (The only difference is that it bypasses any custominspect()
function defined on an object.)It uses syntax-highlighting, smart indentation, removes quotes from keys and just makes the output as pretty as it gets.
and for the command line:
cat package.json | node -e "process.stdin.pipe(new stream.Writable({write: chunk => console.dir(JSON.parse(chunk), {depth: null, colors: true})}))"
Thanks a lot @all! Based on the previous answers, here is another variant method providing custom replacement rules as parameter:
User Pumbaa80's answer is great if you have an object you want pretty printed. If you're starting from a valid JSON string that you want to pretty printed, you need to convert it to an object first:
This builds a JSON object from the string, and then converts it back to a string using JSON stringify's pretty print.