JSON In Python

In this article, we will discuss how to read, write, and parse JSON data in python using the JSON library.

This library allows us to read, write, and parse JSON in order to store and exchange data using versatile data format.

First, import the JSON library.

This library is part of python so we do not need to install it.

import json

How to parse JSON

Parsing a string of JSON data is also called decoding. For that, we can use json.loads(data) method of JSON library.

import json 

jsonString = '{"name": "Mohan", "age": 28, "married": false}'
person = json.loads(jsonString)
print(person)

Output:
{'name': 'Mohan', 'age': 28, 'married': False}

This method converts object to dictionaries, array to lists,  null to none, and the rest of them are recognized as they are and converted to correct types in python.

To know the type of output we can use

print(type(person))

Output:
<class 'dict'>

Encoding or Converting python objects into JSON

for that we can use json.dumps(data) method. let’s understand with an example,

import json 

jsonString = {'name': 'Mohan', 'age': 28, 'married': False}
person = json.dumps(jsonString)
print((person))

Output:
{"name": "Mohan", "age": 28, "married": false}

And it’s return type is

print(type(person))

Output:
<class 'str'>

When we convert from python to JSON. Python object is converted to JSON equivalent.

It converts dict to object,  list and tuple to the array, int, and float to number,  str to string,  none to null. also we can use indent as second parameter for dumps to make it more readable.

We can also sort results alphabetically  by keys :

import json

x = {'name': 'Mohan', 'age': 28, 'married': False}

# sort the result alphabetically by keys:
print(json.dumps(x, indent=4, sort_keys=True))

Output:
{
    "age": 28,
    "married": false,
    "name": "Mohan"
}

How to read JSON file in python:

we can use json.load(filename) to open file. keep in mind that it is different from json.loads() method.

with open('data.json') as json_file:
        data = json.load(json_file)
        // code goes here...

How to write JSON file in python :

first, we need to open the file in write mode.

data = {'name': 'Mohan', 'age': 38 }
with open('data.json', 'w') as json_file:
    json.dump(data, json_file)
    // code goes here...

Command-line Option: 

The JSON file will be validated or pretty-printed. We can use json.tool command followed by file name.

$ python -m json.tool users.json

Output:

[
    {
        "name": "Mohan",
        "age": 20
    },
    {
        "name": "Rohan",
        "age": 26
    }
]

Thank you for the read.

Submit a Comment

Your email address will not be published. Required fields are marked *

Subscribe

Select Categories