开发者

What is meant by to prettify JSON

I have heard of sites开发者_开发问答 that prettify/beautify JSON. What does it actually mean?


This means a more human readable version of it. E.g. the following is valid json, but not well readable:

{"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}

After prettyfying this could look like this:

{
   "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
}


It makes your code pretty, i.e. it indents it, makes sure stuff is aligned in a similar manner, all parenthesis are placed in a similar manner, etc.

Example

var obj = {apple: {red: 5, green: 1}, bananas: 9}; //JS object
var str = JSON.stringify(obj, null, 4); // spacing level 4, or instead of 4 you can write "\t" for tabulator

//The third argument from stringify function enables pretty printing and sets the spacing to use.
console.log(str); //now you can see well pretty printed JSON string in console

But if you want to do it on yourself then you can use the second parameter as a function. More about JSON.stringify function you can find here.

A lot of examples how to pretty print JSON string.


You can see a site here that will beautify pasted JSON...

Its just makes it more readable, mainly for debugging purposed I would imagine.


Like @Heiko Rupp mentioned, it makes easier to read. Most JSON files are already prettified. If you want to prettify your own JSON formatted variable, you can do it like so:

import json

variable = {'a': 1, 'b': 2, 'c': 3}
print(variable)
# returns:
{'a': 1, 'b': 2, 'c': 3}

# prettify
print(json.dumps(variable, indent=4, sort_keys=True))
# returns:
{
    "a": 1,
    "b": 2,
    "c": 3
}
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜