Package: jsonfmt
JSON Formatterjsonfmtis a powerful tool for pretty-printing, querying and conversion JSON documents.It is as powerful asjq, but easier to use.Features1. Pretty print JSON document.Syntax hight and indenation.Read JSON from pipeline.2. Features for handling large JSON document.View a large JSON with pager-mode.Show the overview of a large JSON.Copy the result to clipboard.3. Minimize the JSON document.4. Pick out parts of a large JSON via JMESPath or JSONPath.JMESPath examplesJSONPath examplesQuery for TOML and YAML5. Convert formats between JSON, TOML and YAML.JSON to TOML and YAMLTOML to JSON and YAMLYAML to JSON and TOML6. Modify some values in the input data.Add itemsModify itemsPop items7. Output to file.Install$pipinstalljsonfmtUsage$jsonfmt[options][files...]Positional arguments:files: the files that will be processedOptions:-h, --help: show this help message and exit-c: suppress all whitespace separation-C: copy the result to clipboard-e: escape non-ASCII characters-f {json,toml,yaml}: the format to output (default: same as input)-i {0-8,t}: number of spaces for indentation (default: 2)-o: show data structure overview-O: overwrite the formated text to original file-l {jmespath,jsonpath}: the language for querying (default: jmespath)-p QUERYPATH: the path for querying-s: sort keys of objects on output--set 'foo.k1=v1;k2[i]=v2': set the keys to values (seperated by;)--pop 'k1;foo.k2;k3[i]': pop the specified keys (seperated by;)-v: show the versionExampleThere are some test data in foldertest:test/
|- example.json
|- example.toml
|- example.yaml1. Pretty print JSON document.Syntax hight and indenation.In the Python, there is a built-in tool for format JSON document:python -m json.tool.
But its feature is too simple. Sojsonfmtextends its capabilities, such ashighlight,pager,overview, etc.By default, indentation is 2 spaces. You can specify it with option-i.
The number of spaces allowed is between 0 and 8. Set it totif you want to usetabfor indentation.The-soption is used to sort the output of dictionaries alphabetically by key.If there are some non-ASCII characters in the JSON document, you can use-eto eascape them.$jsonfmt-s-i4test/example.jsonOutput:{"actions":[{"calorie":294.9,"date":"2021-03-02","name":"eat"},{"calorie":-375,"date":"2023-04-27","name":"sport"}],"age":23,"gender":"纯爷们","money":3.1415926,"name":"Bob"}Read JSON from pipeline.Sometimes the JSON you want to process comes from other commands. Just use|to read it from pipeline.$cattest/example.json|jsonfmt-i42. Features for handling large JSON document.View a large JSON with pager-mode.The pager-mode is similar to the commandmore.jsonfmtwill automatically present the result in pager-mode when the JSON document is too large to overflow the window display area.The key-binding of the pager-mode is same as commandmore:keydescriptionjforward  by linekbackward by linefforward by pagectrl+fforward by pagebbackward by pagectrl+bbackward by pageggo to the top of the pageGgo to the bottom/search modeqquit pager-modeThere is a big JSON from GitHub, you can paste this command into terminal to try the pager-mode:curl-s'https://api.github.com/repos/seamile/jsonfmt/commits?per_page=10'|jsonfmtShow the overview of a large JSON.Sometimes we just want to see the overview and don't care about the details of the JSON document. In this case the-ooption can be used.It will clear sublist of the JSON and modify strings to '...' in the overview.If therootnode of the JSON document is a list, only the first child element will be reserved in the overview.$jsonfmt-otest/test.jsonOutput:{"actions":[],"age":23,"gender":"...","money":3.1415926,"name":"..."}Copy the result to clipboard.If you want to copy the result into a file and the output of JSON is more than one page in the terminal, it's going to be hard to do.At this time, you can specify the-Coption to copy the result to the clipboard automatically.$jsonfmt-Ctest/example.json# Outputjsonfmt:resultcopiedtoclipboard.Once you've done the above, you can then usectrl+vorcmd+vto paste the result anywhere on your computer.Note these:When you specify the-Coption, any output destination other than the clipboard will be ignored.When you process multiple files, only the last result will be preserved in the clipboard.3. Minimize the JSON document.The-coption used to suppress all whitespace and newlines to compact the JSON document into a single line.$echo'{"name": "alex","age": 21,"items": ["pen","phone"]}'|jsonfmt-cOutput:{"age":21,"items":["pen","phone"],"name":"alex"}4. Pick out parts of a large JSON via JMESPath or JSONPath.Unlike from jq's private solution,jsonfmtuses bothJMESPathandJSONPathas its query language.Among the many JSON query languages,JMESPathis the most popular one (compared here). It is more general thanjq, and more intuitive and powerful thanJSONPath. So I prefer to use it.Like the XPath for xml,JMESPathcan elegantly extract parts of a given JSON document with simple syntax. The official tutorial of JMESPath ishere.JMESPath examplespick out the first actions inexample.json$jsonfmt-p'actions[0]'test/example.jsonOutput:{"calorie":294.9,"date":"2021-03-02","name":"eat"}Filter all items inactionswithcalorie> 0.$jsonfmt-p'actions[?calorie>`0`]'test/example.jsonOutput:[{"calorie":294.9,"date":"2021-03-02","name":"eat"}]Show all the keys and actions' length.$jsonfmt-p'{all_keys:keys(@), actions_len:length(actions)}'test/example.jsonOutput:{"all_keys":["actions","age","gender","money","name"],"actions_len":2}Sortactionsbycalorieand redefine a dict.$jsonfmt-p'sort_by(actions, &calorie)[].{name: name, calorie:calorie}'test/example.jsonOutput:[{"name":"sport","calorie":-375},{"name":"eat","calorie":294.9}]More examples of JMESPath.JSONPath examplesThe syntax ofJSONPathis very similar to that ofJMESPath. Everything thatJSONPathcan doJMESPathcan also do, except using relative path querying. SoJSONPathcan be used as a supplementary query method ofJMESPath.Filter allnamefields by relative path:# use `-l` to specify the query language of JSON$jsonfmt.py-ljsonpath-p'$..name'test/example.jsonOutput:["Bob","eat","sport"]Query for TOML and YAMLAmazingly, you can do all of the above with TOML and YAML in the same way, and convert the result format arbitrarily. It is even possible to process all three formats simultaneously in a single command.Read the data from toml file, and convert the result to yaml$jsonfmt-p'{all_keys:keys(@), actions_len:length(actions)}'test/example.toml-fyamlOutput:all_keys:-age-gender-money-name-actionsactions_len:2Handle three formats simultaneously$jsonfmt.py-p'actions[0]'test/example.jsontest/example.tomltest/example.yamlOutput:{
    "calorie": 294.9,
    "date": "2021-03-02",
    "name": "eat"
}

calorie = 294.9
date = "2021-03-02"
name = "eat"

calorie: 294.9
date: '2021-03-02'
name: eat5. Convert formats between JSON, TOML and YAML.Thejsonfmtcan recognize any format of JSON, TOML and YAML from files orstdin. Either formats can be converted to the other by specifying the "-f" option.Note that:The `null` value is invalid in TOML. Therefore, any null values from JSON or YAML will be removed when converting to TOML.JSON to TOML and YAML$jsonfmttest/example.json-ftomlOutput:age=23gender="纯爷们"money=3.1415926name="Bob"[[actions]]calorie=294.9date="2021-03-02"name="eat"[[actions]]calorie=-375date="2023-04-27"name="sport"$jsonfmttest/example.json-fyamlOutput:actions:-calorie:294.9date:'2021-03-02'name:eat-calorie:-375date:'2023-04-27'name:sportage:23gender:纯爷们money:3.1415926name:BobTOML to JSON and YAML# toml to json$jsonfmttest/example.toml-fjson# toml to yaml$jsonfmttest/example.toml-fyamlYAML to JSON and TOML# yaml to json$jsonfmttest/example.yaml-fjson# yaml to toml$jsonfmttest/example.yaml-ftoml6. Modify some values in the input data.Use the--setand--popoptions when you want to change something in the input documents.The format is--set 'key=value'. When you need to modify multiple values ​​you can use;to separate:--set 'k1=v1;k2=v2'. If the key-value pair dose not exist, it will be added.For the items in list, usekey[i]orkey.ito specify. If the index is greater than or equal to the number of elements, the value will be appended.Add items# add `country` key and append one item for `actions`$jsonfmt--set'country=China; actions[2]={"name": "drink"}'test/example.jsonOutput:{"actions":[{"calorie":294.9,"date":"2021-03-02","name":"eat"},{"calorie":-375,"date":"2023-04-27","name":"sport"},{"name":"drink"}],"age":23,"country":"China","gender":"纯爷们","money":3.1415926,"name":"Bob"}Modify items# modify money and actions[1]["name"]$jsonfmt--set'money=1000; actions[1].name=swim'test/example.jsonOutput:{"actions":[{"calorie":294.9,"date":"2021-03-02","name":"eat"},{"calorie":-375,"date":"2023-04-27","name":"swim"}],"age":23,"gender":"纯爷们","money":1000,"name":"Bob"}Pop items# pop `gender` and actions[1]$jsonfmt--pop'gender; actions[1]'test/example.jsonOutput:{"actions":[{"calorie":294.9,"date":"2021-03-02","name":"eat"}],"age":23,"money":3.1415926,"name":"Bob"}Of course you can use--setand--poptogether.jsonfmt--set'skills=["Django","Flask"];money=1000'--pop'gender;actions[1]'test/example.jsonNote, however, that the above command will not modify the original JSON file.
If you want to do this, read below please.7. Output to file.use the-Oparameter to overwrite the file with the result.This option will be forced to close when-ois specified$jsonfmt--set'name=Alex'-Otest/example.jsonwrite the result to a new file (use symbol>).$jsonfmttest/example.json>formatted.json