DEV Community

loading...
Cover image for All You Need To Know About Python JSON Module

All You Need To Know About Python JSON Module

Aya Bouchiha
Full stack web developer
・4 min read

Hello everybody,
I'm Aya Bouchiha,
on this amazing day, we'll discuss using the JSON module in python

What's JSON

JSON: (JavaScript Object Notation) is a syntax for serializing objects, arrays, numbers, strings, booleans, and null. It is based upon JavaScript syntax but is distinct from it: some JavaScript is not JSON.

JSON Syntax rules

  • Data have to be written as key-value pairs.
  • Data is separated by commas.
  • Curly braces hold objects.
  • Square brackets hold arrays.
  • string has to be written inside double quotes "", instead of single quotes ''.
[
    {
        "id": 1,
        "name": "Aya Bouchiha",
        "job": "full-stack developer",
        "contact_info": {
            "email": "developer.aya.b@gmail.com",
            "telegram": "https://t.me/AyaBouchiha"
        },
        "isMoroccan": true,
        "facebook_account": null,
        "favorite_subjects": [
            "programming",
            "math",
            "physics",
            "english",
            "french"
        ]
    }
]
Enter fullscreen mode Exit fullscreen mode

Example of a JSON file

tasks.json

[
    {
        "id": 1,
        "username": "Aya Bouchiha",
        "title": "eat fruits",
        "completed": true
    },
    {
        "id": 2,
        "username": null,
        "title": "go to gym",
        "completed": true
    },
    {
        "id": 3,
        "username": null,
        "title": "drink an orange jus",
        "completed": true
    },
    {
        "id": 4,
        "username": "John Doe",
        "title": "practice english",
        "completed": false
    }
]
Enter fullscreen mode Exit fullscreen mode

Using JSON in python

Python objects and their equivalent conversion to JSON

python json
str string
int, long or float number
list array
dict object
True true
False false
None null

Importing JSON module in python

json is a built-in package in python for encoding and decoding JSON data.

import json
Enter fullscreen mode Exit fullscreen mode

Serializing JSON

json.dumps

json.dumps(): lets you convert a python dictionary to JSON as a string.

import json

task = {
        'id': 1,
        'username': None,
        'title': 'eat fruits',
        'completed': True
}

print(json.dumps(task))
Enter fullscreen mode Exit fullscreen mode

Output:

{"id": 1, "name": null, "title": "eat fruits", "completed": true}

<class 'str'>
Enter fullscreen mode Exit fullscreen mode

json.dump()

json.dump() lets you converts a python dictionnary to JSON in a specified file.

import json

user_dict =  {
    'id': 1,
    'name': 'Aya Bouchiha',
    'job': 'full-stack developer',
    'contact_info': {
       'email': 'developer.aya.b@gmail.com',
       'telegram': 'https://t.me/AyaBouchiha'
    },
   'isMoroccan': True,
   'facebook_account': None,
   'favorite_subjects': ['programming', 'math', 'physics', 'english', 'french']
}


with open('user.json', "w") as user_file:
    json.dump(user_dict, user_file)
Enter fullscreen mode Exit fullscreen mode

Output:

user.json

{"id": 1, "name": "Aya Bouchiha", "job": "full-stack developer", "contact_info": {"email": "developer.aya.b@gmail.com", "telegram": "https://t.me/AyaBouchiha"}, "isMoroccan": true, "facebook_account": null, "favorite_subjects": ["programming", "math", "physics", "english", "french"]}
Enter fullscreen mode Exit fullscreen mode

There is a problem here, we find that our json data is not organized and not easy to read, that's why the indent parameter comes, it lets you specify the indentation size for nested structures. this parameter takes by default None. To understand better let's try the same example with an indentation size of 2.

with open('user.json', "w") as user_file:
    json.dump(user_dict, user_file, indent=2)
Enter fullscreen mode Exit fullscreen mode

Output:

user.json

{
  "id": 1,
  "name": "Aya Bouchiha",
  "job": "full-stack developer",
  "contact_info": {
    "email": "developer.aya.b@gmail.com",
    "telegram": "https://t.me/AyaBouchiha"
  },
  "isMoroccan": true,
  "facebook_account": null,
  "favorite_subjects": [
    "programming",
    "math",
    "physics",
    "english",
    "french"
  ]
}
Enter fullscreen mode Exit fullscreen mode

What about indent=4 :) ?

with open('user.json', "w") as user_file:
    json.dump(user_dict, user_file, indent=4)
Enter fullscreen mode Exit fullscreen mode

Output:

user.json

{
    "id": 1,
    "name": "Aya Bouchiha",
    "job": "full-stack developer",
    "contact_info": {
        "email": "developer.aya.b@gmail.com",
        "telegram": "https://t.me/AyaBouchiha"
    },
    "isMoroccan": true,
    "facebook_account": null,
    "favorite_subjects": [
        "programming",
        "math",
        "physics",
        "english",
        "french"
    ]
}
Enter fullscreen mode Exit fullscreen mode

Now, our json file looks better, but how can we sort our keys?

sort_keys: lets you sort keys in ascending order if it is True, however, sort_keys takes by default False.
Let's take an example

import json

user_dict =  {
    'id': 1,
    'name': 'Aya Bouchiha',
    'job': 'full-stack developer',
    'contact_info': {
       'email': 'developer.aya.b@gmail.com',
       'telegram': 'https://t.me/AyaBouchiha'
    },
   'isMoroccan': True,
   'facebook_account': None,
   'favorite_subjects': ['programming', 'math', 'physics', 'english', 'french']
}


with open('user.json', "w") as user_file:
    json.dump(user_dict, user_file, indent=4, sort_keys=True)
Enter fullscreen mode Exit fullscreen mode

Output:

user.json

{
    "contact_info": {
        "email": "developer.aya.b@gmail.com",
        "telegram": "https://t.me/AyaBouchiha"
    },
    "facebook_account": null,
    "favorite_subjects": [
        "programming",
        "math",
        "physics",
        "english",
        "french"
    ],
    "id": 1,
    "isMoroccan": true,
    "job": "full-stack developer",
    "name": "Aya Bouchiha"
}
Enter fullscreen mode Exit fullscreen mode

Note:

You can use indent and sort_key parameters in json.dump() and also json.dumps().

Deserializing JSON

json.loads()

json.loads(): translate JSON string to a Python object.

import json

user_json ='''[
    {
        "id": 1,
        "name": "Aya Bouchiha",
        "job": "full-stack developer",
        "contact_info": {
            "email": "developer.aya.b@gmail.com",
            "telegram": "https://t.me/AyaBouchiha"
        },
        "isMoroccan": true,
        "facebook_account": null,
        "favorite_subjects": [
            "programming",
            "math",
            "physics",
            "english",
            "french"
        ]
    }
]'''

user = json.loads(user_json)

print(user)
print(type(user))
Enter fullscreen mode Exit fullscreen mode

Output:

[{'id': 1, 'name': 'Aya Bouchiha', 'job': 'full-stack developer', 'contact_info': {'email': 'developer.aya.b@gmail.com', 'telegram': 'https://t.me/AyaBouchiha'}, 'isMoroccan': True, 'facebook_account': None, 'favorite_subjects': ['programming', 'math', 'physics', 'english', 'french']}]
<class 'list'>
Enter fullscreen mode Exit fullscreen mode

json.load()

json.load(): lets you read a JSON document from a file and translate it to a python object.

user.json

[
    {
        "id": 1,
        "name": "Aya Bouchiha",
        "job": "full-stack developer",
        "contact_info": {
            "email": "developer.aya.b@gmail.com",
            "telegram": "https://t.me/AyaBouchiha"
        },
        "isMoroccan": true,
        "facebook_account": null,
        "favorite_subjects": [
            "programming",
            "math",
            "physics",
            "english",
            "french"
        ]
    }
]
Enter fullscreen mode Exit fullscreen mode

file.py:

import json

with open('user.json', 'r') as user_file:
    user = json.load(user_file)

print(user)
print(type(user))
Enter fullscreen mode Exit fullscreen mode

output:

[{'id': 1, 'name': 'Aya Bouchiha', 'job': 'full-stack developer', 'contact_info': {'email': 'developer.aya.b@gmail.com', 'telegram': 'https://t.me/AyaBouchiha'}, 'isMoroccan': True, 'facebook_account': None, 'favorite_subjects': ['programming', 'math', 'physics', 'english', 'french']}]
<class 'list'>
Enter fullscreen mode Exit fullscreen mode

Summary

JSON: (JavaScript Object Notation) is a syntax for serializing objects, arrays, numbers, strings, booleans, and null.

json.dumps(): converts a python dictionnary to JSON as a string.

json.dump() converts a python dictionnary to JSON in a specified file.

json.loads(): translate JSON string to a Python object.

json.load(): lets you read a JSON document from a file and translate it to a python object.

References & Useful Ressources

To Contact Me:

email: developer.aya.b@gmail.com

telegram: Aya Bouchiha

Have a great day!

Discussion (0)