All You Need To Know About Python JSON Module

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 ba…


This content originally appeared on DEV Community and was authored by Aya Bouchiha

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"
        ]
    }
]

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
    }
]

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

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))

Output:

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

<class 'str'>

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)

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"]}

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)

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"
  ]
}

What about indent=4 :) ?

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

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"
    ]
}

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)

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"
}

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))

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'>

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"
        ]
    }
]

file.py:

import json

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

print(user)
print(type(user))

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'>

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!


This content originally appeared on DEV Community and was authored by Aya Bouchiha


Print Share Comment Cite Upload Translate Updates
APA

Aya Bouchiha | Sciencx (2021-07-31T00:57:48+00:00) All You Need To Know About Python JSON Module. Retrieved from https://www.scien.cx/2021/07/31/all-you-need-to-know-about-python-json-module/

MLA
" » All You Need To Know About Python JSON Module." Aya Bouchiha | Sciencx - Saturday July 31, 2021, https://www.scien.cx/2021/07/31/all-you-need-to-know-about-python-json-module/
HARVARD
Aya Bouchiha | Sciencx Saturday July 31, 2021 » All You Need To Know About Python JSON Module., viewed ,<https://www.scien.cx/2021/07/31/all-you-need-to-know-about-python-json-module/>
VANCOUVER
Aya Bouchiha | Sciencx - » All You Need To Know About Python JSON Module. [Internet]. [Accessed ]. Available from: https://www.scien.cx/2021/07/31/all-you-need-to-know-about-python-json-module/
CHICAGO
" » All You Need To Know About Python JSON Module." Aya Bouchiha | Sciencx - Accessed . https://www.scien.cx/2021/07/31/all-you-need-to-know-about-python-json-module/
IEEE
" » All You Need To Know About Python JSON Module." Aya Bouchiha | Sciencx [Online]. Available: https://www.scien.cx/2021/07/31/all-you-need-to-know-about-python-json-module/. [Accessed: ]
rf:citation
» All You Need To Know About Python JSON Module | Aya Bouchiha | Sciencx | https://www.scien.cx/2021/07/31/all-you-need-to-know-about-python-json-module/ |

Please log in to upload a file.




There are no updates yet.
Click the Upload button above to add an update.

You must be logged in to translate posts. Please log in or register.