Python JSON

In this tutorial, we will learn about Python JSON with the help of examples.

JSON stands for Javascript Object Notation. JSON is a text-based data format that is used to transfer data.

JSON is primarily used to transmit data between a server and web applications.


json Module in Python

Python comes with a built-in package called json to work with JSON files. We first need to import the json module before we can use it.

import json 

Once we import the json module, we can easily parse JSON strings.


Parse JSON: JSON to Python Conversion

In Python, we use the json.loads() function to parse a JSON string. The obtained result will be a Python Dictionary.

Let's see an example,

import json

# JSON string
employee = '{"name": "Johnny", "hobbies": ["Chess", "Piano", "Sing"]}'

# parse employee
employee_dict = json.loads(employee)

# print employee_dict dictionary
print('Dictionary:', employee_dict)

# print values of hobbies key
print('Values of hobbies key:', employee_dict['hobbies'])

Output

Dictionary: {'name': 'Johnny', 'hobbies': ['Chess', 'Piano', 'Sing']}
Values of hobbies key: ['Chess', 'Piano', 'Sing']

In the above example, we first imported the json module and used the json.load() module to parse a JSON string.

Since, the parsed JSON employee_dict is a dictionary, we have used the key named hobbies to access all its values.


Python to JSON Conversion

We use the json.dumps() function to convert a dictionary to JSON string in Python. For example,

import json

# employee_dict dictionary
employee_dict = {'name': 'Johnny', 'hobbies': ['Chess', 'Piano', 'Sing']}

# use of dumps() to convert dictionary to JSON string
employee_json = json.dumps(employee_dict)

# print JSON string
print(employee_json)

Output

{"name": "Johnny", "hobbies": ["Chess", "Piano", "Sing"]}

Read JSON Files in Python

In Python, we use the open() function to read and the load() function to parse json files.

Let's suppose we have a json file named employee.json:

{
"name": "Johnny", 
"hobbies": ["Chess", "Piano", "Sing"]
}

Now here's how we read and parse this employee.json file,

import json

with open('employee.json', 'r') as json_file:
  result = json.load(json_file)

# display result dictionary
print(result)

Output

{'name': 'Johnny', 'hobbies': ['Chess', 'Piano', 'Sing']}

Here, we have used the open() function to read the json file named employee.json.

After that we have used the json.load() function to parse employee.json which gives us a dictionary named result.


Python Objects and JSON Equivalence

Python Object JSON Object
dict object
str string
list, tuple array
Int, float number
None null
True true
False false

Write JSON to a File

In Python, we use the open() function to open the file in writing mode and the dump() function to write json to a file in Python. For example,

import json

employee_dict = {'name': 'Johnny',
'role': 'Developer',
'age': 24,
'hobbies': ['Chess', 'Piano', 'Sing']
}

with open('employee.txt', 'w') as json_file:
  json.dump(employee_dict, json_file)

In the above example, we have used the open() function to open the file named 'employee.txt' in writing mode using 'w'.

We then used the json.dump() function to convert employee_dict to JSON string. And finally the JSON string is saved in the employee.txt file.


JSON Pretty Print in Python

The JSON data above is not easily readable. To analyze and debug JSON data, we need it to be in a more readable format.

We can make JSON data more readable by adding indentations, line breaks, etc.

Let's see how we can prettify JSON data,

import json

employee_string = '{"name": "Johnny", "role": "Developer", "age": 24, "hobbies": ["Chess", "Piano", "Sing"]}'

# getting dictionary
employee_dict = json.loads(employee_string)

# pretty print JSON string 
print(json.dumps(employee_dict, indent = 4,sort_keys = False))

Output

{
    "name": "Johnny",
    "role": "Developer",
    "age": 24,
    "hobbies": [
        "Chess",
        "Piano",
        "Sing"
    ]
}

Here, we have passed in three parameters inside the json.dumps() function,

  • employee_dict - parsed json string
  • indent = 4 - number of idents is equal to 4
  • sort_keys = False - the keys will not be sorted

As we can see from the output, this JSON data is much more readable compared to the default one.

Did you find this article helpful?