How to format a minified JSON file in Linux terminal


1. Using jq command

If we have this minified compact JSON from a curl output or a file downloaded from the internet:

{"errors":[{"errors":[{"id":1,"code":"ERR_ParseError","field":"Row","message":"Row 1 could not be imported.","parameters":null}]},{"errors":[{"id":2,"code":"ERR_MissingRequiredFields","field":"Row","message":"Row 2 does not have a Parameter","parameters":null}]},{"errors":[{"id":3,"code":"ERR_ParseError","field":"Row","message":"Row 3 could not be imported.","parameters":null}]},{"errors":[{"id":4,"code":"ERR_DoesNotExist","field":"Object","message":"Object dsasdadas does not exist.","parameters":{"Parameter1":"dsasdadas","Parameter2":""}}]}]}

We can make it into readable form by using the jq command:

$ sudo apt install jq

To use it:

$ cat file.json | jq

This prints in stdout the extended JSON file:

{ "errors": [ { "errors": [ { "id": 1, "code": "ERR_ParseError", "field": "Row", "message": "Row 1 could not be imported.", "parameters": null } ] }, { "errors": [ { "id": 2, "code": "ERR_MissingRequiredFields", "field": "Row", "message": "Row 2 does not have a Parameter.", "parameters": null } ] }, { "errors": [ { "id": 3, "code": "ERR_ParseError", "field": "Row", "message": "Row 3 could not be imported.", "parameters": null } ] }, { "errors": [ { "id": 4, "code": "ERR_DoesNotExist", "field": "Object", "message": "Object dsasdadas does not exist.", "parameters": { "Parameter1": "dsasdadas", "Parameter2": "" } } ] } ] }

If we want to save it into a file:

$ cat file.json | jq > human.json

2. Using python3 with a module

Instead of installing a new program, it is possible to do this with a standard module in python3:

$ python3 -m json.tool file.json