example for json in python

In this examples, you will learn to convert JSON object to python and convert python to JSON object.

JSON : JavaScript Object Notation is a format for structuring data. It is mainly used for storing and transferring data between the browser and the server. Python has built-in package JSON for handling JSON operation like, creating JSON object, parsing JSON object, serializing, desterilizing.

Here is simple JSON string :

    
        book = '{"name": "Python Examples", "access": ["English", "French"]}'
    

Convert from JSON to Python

JSON loads() method can be used to parse a valid JSON string and convert it into a Python Dictionary.

Example - 1: JSON load

    
#python program for load json
import json

book_json = '{"name": "Python Examples", "access": ["English", "French"]}'

book = json.loads(book_json)

print(book)
print(book['name'])
   

Output :

    
{'name': 'Python Examples', 'access': ['English', 'French']}
Python Examples
    

Convert from Python to JSON

JSON dumps() method converts python object into JSON string.

Example - 2: JSON dumps

    
#python program for JSON dumps
import json

book = {'name': 'Python Examples', 'access': ['English', 'French']}

book_json = json.dumps(book);

print(book_json)
print(book)
   

Output :

    
{"name": "Python Examples", "access": ["English", "French"]}
    

Format JSON Data

We can use the dumps() method to get the pretty formatted JSON string with using indent.

Example - 3: Format JSON Data

    
#python program for print formatted JSON data
import json

book = {'name': 'Python Examples', 'access': ['English', 'French', 'Arabic']}

book_json = json.dumps(book, indent = 4);

print(book_json)
   

Output :

    
{
    "name": "Python Examples",
    "access": [
        "English",
        "French",
        "Arabic"
    ]
}
    

Order JSON Data

We can also order JSON data with sort_keys=True parameter while json.dumps. It will automatically sorts all JSON data.

Example - 3: Sorting JSON Data

    
#python program for print sorted JSON data
import json

book = {'name': 'Python Examples', 'access': ['English', 'French', 'Arabic']}

book_json = json.dumps(book, indent = 4, sort_keys=True);

print(book_json)
   

Output :

    
{
    "access": [
        "English",
        "French",
        "Arabic"
    ],
    "name": "Python Examples"
}
    

As per example, it will only sorts keys. like in python object name is first element and access is second element and access has three value with random order then it will sort only keys to acceding order.


Share your thoughts

Ask anything about this examples