DEV Community

Anurag Rana
Anurag Rana

Posted on • Originally published at pythoncircle.com on

2 2

Python Script to Validate, format and Beautify JSON string

As per official JSON website, JSON is a light-weight data interchange format. It is easy for humans to read and write. It is easy for machines to parse and generate. It is based on a subset of the JavaScript Programming Language, Standard ECMA-262 3rd Edition — December 1999.

In this small article we will see how to validate and format the JSON string using python.

Format JSON string:

import json

json_string = '{"first_name": "Anurag", "last_name":"Rana", "key3": {"key1":"key2"}}'

try:
    parsed_json = json.loads(json_string)
    print(json.dumps(parsed_json, indent = 4,sort_keys=False))
except Exception as e:
    print(repr(e))
Enter fullscreen mode Exit fullscreen mode

output:

rana@Brahma: scripts$ python3 jsonParse.py 
{
    "first_name": "Anurag",
    "last_name": "Rana",
    "key3": {
       "key1": "key2"
    }
}
rana@Brahma: scripts$
Enter fullscreen mode Exit fullscreen mode

Parameter indent decides the number of spaces to use for indentation. Parameter sort_keys decides whether the keys in formatted JSON should be in sorted order or not. The default value is False.

Format JSON file:

We can use the same code to format and validate the JSON file. Place a .json file with below content in the current working directory.

{"a": "b","c": "d","e": ["f","g","h"]}
Enter fullscreen mode Exit fullscreen mode

Now use this piece of code to format the json file.

import json

json_string = None

with open("json_file.json") as f:
    json_string = f.read()
try:
    parsed_json = json.loads(json_string)
    formatted_json = json.dumps(parsed_json, indent = 4,sort_keys=True)
    with open("json_file.json","w") as f:
    f.write(formatted_json)
except Exception as e:
    print(repr(e))
Enter fullscreen mode Exit fullscreen mode

Error in JSON validation:

Any error in JSON string will be reported with exact location in string.

For example, a comma is missing in below JSON string.

import json

json_string = '{"first_name": "Anurag" "last_name":"Rana", "key3": {"key1":"key2"}}'

try:
    parsed_json = json.loads(json_string)
    print(json.dumps(parsed_json, indent = 4,sort_keys=True))
except Exception as e:
    print(repr(e))
Enter fullscreen mode Exit fullscreen mode

output:

JSONDecodeError("Expecting ',' delimiter: line 1 column 25 (char 24)",)
Enter fullscreen mode Exit fullscreen mode

Bonus:

You can pretty-print the small JSON string directly at command terminal without using python script file. Use below line of code.

echo '{"first_name": "Anurag", "last_name": "rana"}' | python -m json.tool
Enter fullscreen mode Exit fullscreen mode

output:

{
 "first_name": "Anurag",
 "last_name": "rana"
}
Enter fullscreen mode Exit fullscreen mode

You can add this crome app to your browser to validate and beautify the JSON strings.

Originally published at www.pythoncircle.com.

More from https://www.pythoncircle.com

Sentry image

Hands-on debugging session: instrument, monitor, and fix

Join Lazar for a hands-on session where you’ll build it, break it, debug it, and fix it. You’ll set up Sentry, track errors, use Session Replay and Tracing, and leverage some good ol’ AI to find and fix issues fast.

RSVP here →

Top comments (0)

A Workflow Copilot. Tailored to You.

Pieces.app image

Our desktop app, with its intelligent copilot, streamlines coding by generating snippets, extracting code from screenshots, and accelerating problem-solving.

Read the docs