Parsing JSON Data in Python

Posted 

3 min read

JSON is a human-readable text-based data format. It is language independent and used for data interchange between applications.

In this article, we’ll explain how to parse JSON data in Python.

Python JSON

The json module that allows you to encode and decode JSON data is a part of the Python standard library.

JSON is a string that represents data. Encoding or serialization means transforming a Python object into a JSON string that can be stored in a file or transmitted over the network. Decoding or de-serialization the reverse process of encoding where a JSON string is transformed into Python object.

Below is a table showing Python objects and their equivalent JSON representation:

PythonJSON
dictobject
list, tuplearray
strstring
int, floatnumber
Truetrue
Falsefalse
Nonenull

To work with JSON simply import the module at the top of your file:

import json

Encoding JSON in Python

The json module has two methods for encoding Python objects into JSON formatted strings: dump() and dumps().

The dump() method sends the output to a file-like object. It takes two positional arguments: the object to be encoded and the file-like object. Here is an example:

data = {
    "country": "Germany",
    "vehicle": {
        "name": "Volkswagen",
        "model": "T-Roc"
    }
}

with open("file.json", "w") as file:
    json.dump(data, file)

If you run the script it will create a file named file.json:

file.json
{"country": "Germany", "vehicle": {"name": "Volkswagen", "model": "T-Roc"}}

The dumps() method works same as dump() but instead of sending the output to a file-like object, it returns a string:

data = {
    "country": "Germany",
    "vehicle": {
        "name": "Volkswagen",
        "model": "T-Roc"
    }
}

json.dumps(data)
'{"country": "Germany", "vehicle": {"name": "Volkswagen", "model": "T-Roc"}}'

Both methods accept same keyword arguments. For example if you are analyzing or debugging the JSON dat you may want to specify the indentation level:

data = {
    "country": "Germany",
    "vehicle": {
        "name": "Volkswagen",
        "model": "T-Roc"
    }
}

print(json.dumps(data, indent=2))
{
  "country": "Germany",
  "vehicle": {
    "name": "Volkswagen",
    "model": "T-Roc"
  }
}

Decoding JSON in Python

To transform JSON encoded data into Python objects, use the load() and loads() methods.

The load() method reads JSON structure from a file-like object and transforms it into a Python object.

Let’s say we have the following JSON file:

file.json
[
  {
    "userId": 1,
    "id": 1,
    "title": "Meet with Lisa",
    "completed": true
  },
  {
    "userId": 1,
    "id": 2,
    "title": "Design a prototype",
    "completed": false
  }
]

To transform the JSON data to a Python representation, you would use something like this:

import json

with open('file.json') as f:
  data = json.load(f)

type(data)

The JSON is transformed into a Python list, that you can use in your code:

<class 'list'>

The loads() method converts a string containing a JSON document to a Python object:

import json

json_str= '{"userId": "1", "id": "1", "title": "Meet with Lisa", "completed": "True"}'

print(json.loads(json_str))

The string is transformed into a Python dictionary:

{'userId': '1', 'id': '1', 'title': 'Meet with Lisa', 'completed': 'True'}

Here is a more advanced example that shows how to make an api request and decode the JSON data:

import json
import requests

response = requests.get("https://jsonplaceholder.typicode.com/users")
users = json.loads(response.text)

print(users)

Conclusion

We’ve hows you how to encode and decode JSON data in Python.

If you have any questions or feedback, feel free to leave a comment.