Python Script to Validate, format and Beautify JSON string
Tags: python, json
Published: 2019-06-25 16:09:19

---
title: Python Script to Validate, format and Beautify JSON string
published: true
tags: python, json
canonical_url: https://www.pythoncircle.com/post/576/python-script-3-validate-format-and-beautify-json-string-using-python/
---

![](https://cdn-images-1.medium.com/max/960/1*GbIQPCAmgZabjDkMhH58Gg.jpeg)

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](http://www.json.org/) string using python.


**Format JSON string:**

```python
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:**

```
rana@Brahma: scripts$ python3 jsonParse.py 
{
    "first_name": "Anurag",
    "last_name": "Rana",
    "key3": {
       "key1": "key2"
    }
}
rana@Brahma: 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. 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.

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

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

```python
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.

```python
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:**

```python
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.

```bash
echo '{"first_name": "Anurag", "last_name": "rana"}' | python -m json.tool
```

**output:**

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

You can add [this crome app](https://chrome.google.com/webstore/detail/json-borne-json-validator/jdlfgjpngcbjpdkbobhijcpfaainabai) to your browser to validate and beautify the JSON strings.


_Originally published at_ [_www.pythoncircle.com_](https://www.pythoncircle.com/post/576/python-script-3-validate-format-and-beautify-json-string-using-python/)_._

More from [https://www.pythoncircle.com](https://www.pythoncircle.com)

- [**How To Host Django App On Pythonanywhere For Free**](https://www.pythoncircle.com/post/18/how-to-host-django-app-on-pythonanywhere-for-free/)
- [**Difference Between List, Set And Tuples In Python And More Such Comparisons**](https://www.pythoncircle.com/post/249/difference-between-list-set-and-tuples-in-python-and-more-such-comparisons/)
- [**How To Create Completely Automated Telegram Channel With Python**](https://www.pythoncircle.com/post/265/how-to-create-completely-automated-telegram-channel-with-python/)
- [**Elastic Search With Kibana And Django**](https://www.pythoncircle.com/post/291/elastic-search-with-kibana-and-django/)