简体   繁体   中英

Pretty print complex JSON input

I have gone through How can I pretty-print JSON in (unix) shell script? and other Stackoverflow posts on "pretty print JSON" but they are only good for simple inputs like,

echo '{"foo": "lorem", "bar": "ipsum"}' | python -m json.tool

When I try to do something like this

echo '{"group" : {list : [1,2,3]}, "list" : ["a","b","c"]}' | python -m json.tool

it fails.

Gives me the error

Expecting property name enclosed in double quotes: line 1 column 13 (char 12)

PS: Why am I trying to pass a complex json input? I'm trying to solve question 1 from here


Edit: Thanks for prompt reply. But what if I'm looking for an output like this

{

"group" : {

"list" : [1,2,3]

},

"list" : ["a","b","c"]

}

Your JSON input is invalid; you need to quote the first list key:

echo '{"group" : {"list" : [1,2,3]}, "list" : ["a","b","c"]}' | python -m json.tool
#                 ^^^^^^

The tool can handle any complexity of JSON, provided you give it valid JSON input. With the error corrected, Python outputs:

$ echo '{"group" : {"list" : [1,2,3]}, "list" : ["a","b","c"]}' | python -m json.tool
{
    "group": {
        "list": [
            1,
            2,
            3
        ]
    },
    "list": [
        "a",
        "b",
        "c"
    ]
}

In this line:

"group" : {list : [1,2,3]}

you have invalid json. it is expecting list to be a string, which is not. Hence the error. Changing:

"group" : {"list" : [1,2,3]}

will solve the issue.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM