Python Script 3: Validate, format and Beautify JSON string Using Python

Python Script 3: Validate, format and Beautify JSON string Using Python

Python Script 3:Validate, format and Beautify JSON string Using Python - 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

Python Script 3:Validate, format and Beautify JSON string Using Python - 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

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))

output:

[email protected]: scripts$ python3 jsonParse.py 
{
    "first_name": "Anurag",
    "last_name": "Rana",
    "key3": {
        "key1": "key2"
    }
}
[email protected]: scripts$ 

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. Default value is False.

Format JSON file:

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

{"a": "b","c": "d","e": ["f","g","h"]}

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))

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))

output:

JSONDecodeError("Expecting ',' delimiter: line 1 column 25 (char 24)",)

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

*output: *

{
    "first_name": "Anurag",
    "last_name": "rana"
}

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

Angular 9 Tutorial: Learn to Build a CRUD Angular App Quickly

What's new in Bootstrap 5 and when Bootstrap 5 release date?

Brave, Chrome, Firefox, Opera or Edge: Which is Better and Faster?

How to Build Progressive Web Apps (PWA) using Angular 9

What is new features in Javascript ES2020 ECMAScript 2020

Python Tutorial: Working with JSON Data using the json Module

In this Python Programming Tutorial, we will be learning how to work with JSON data. We will learn how to load JSON into Python objects from strings and how to convert Python objects into JSON strings. We will also see how to load JSON from a file and save those Python objects back to files

Top Python Development Companies | Hire Python Developers

After analyzing clients and market requirements, TopDevelopers has come up with the list of the best Python service providers. These top-rated Python developers are widely appreciated for their professionalism in handling diverse projects. When...

JSON — The Python Way

JSON — The Python Way JSON: The Fat-Free Alternative to XML.