Write and Parse JSON in Python

CParse JSON in CWrite JSON in C

Python has a JSON package that supports native JSON parsers and writers. So, Python does not require any external package or code to take care of JSON data. We can simply import json and start the manipulation of JSON data. Let's discuss how to read and write JSON in python.

Consider the following sample JSON Document which consists of JSON Array, JSON Object, and key-value pair forms :

{
    "name" : "File.mp3",
    "size" : "25Mb",
    "section" : [ 1 , 2, 3 , 4 ],
    "updateby" : [
     {
         "name" : "user one",
         "date" : "10:00 21 May",
         "userrole" : [ "add", "update", "delete"]
     },
     {
         "name" : "user two",
         "date" : "10:00 21 May",
         "userrole" : [ "add", "delete"]
     }],
    "Metadata" : { "create" : "21 MAy", "audio" : "acc", "video" : "H264"}
}

Setup

In the python project, no special configuration is necessary to process JSON data. Simply add the following line to manipulate JSON Object.

import json


Write JSON in Python

STEP 1: To write JSON, First, you need to import json. With the help of the dumps() method we can convert dict (Python object) into JSON.

import json

# Create JSON Object
jsonData = json.loads("{}")

STEP 2: To create a JSON Array, we need to create an array dict and add into the json object,

intArray = arr.array('d', [1, 2, 3, 4])

# Array add in JSON Object
jsonData["section"] = intArray.tolist()

STEP 3: To create a nested JSON Object, We can create another dictionary or we can take another JSON object and assign it to the respective JSON key.

# create JSON Object
metaDataJsonObj = json.loads("{}")
metaDataJsonObj["create"] = "21 MAy"
metaDataJsonObj["audio"]  = "acc"
metaDataJsonObj["video"]  = "H264"

jsonData["Metadata"] = metaDataJsonObj

STEP 4: Similarly, we can create key-value pair by assigning value to the respective JSON key.

jsonData["name"] = "File.mp3"
jsonData["size"] = "369Mb"

Let's see a complete code of write JSON data in Python :

import json
import array as arr

def JsonWriteInPython():
    """
    Write/Create JSON in python
    """
    print("Let's write/create JSON in Python.")
    try:
        # Create JSON Object
        jsonData = json.loads("{}")

        jsonData["name"] = "File.mp3"
        jsonData["size"] = "File.mp3"

        # Create Array
        intArray = arr.array('d', [1, 2, 3, 4])

        # Array add in JSON Object
        jsonData["section"] = intArray.tolist()

        # create JSON Object
        updateByDataJsonObj_one = json.loads("{}")
        updateByDataJsonObj_one["name"] = "user one"
        updateByDataJsonObj_one["date"] = "10:00 21 May"
        updateByDataJsonObj_one["userrole"] = [ "add", "update", "delete"]

        # create JSON Object
        updateByDataJsonObj_two = json.loads("{}")
        updateByDataJsonObj_two["name"] = "user one"
        updateByDataJsonObj_two["date"] = "10:00 21 May"
        updateByDataJsonObj_two["userrole"] = [ "add", "delete"]

        jsonData["updateby"] = [ updateByDataJsonObj_one, updateByDataJsonObj_two]

        # create JSON Object
        metaDataJsonObj = json.loads("{}")
        metaDataJsonObj["create"] = "21 MAy"
        metaDataJsonObj["audio"]  = "acc"
        metaDataJsonObj["video"]  = "H264"

        jsonData["Metadata"] = metaDataJsonObj


        print("Output JSON : ")
        print(json.dumps(jsonData))
        return jsonData
    except Exception as err:
        print("The err thrown while excuting the code", err)
        return


Parse JSON in Python

STEP 1:To parse JSON, we can use json.loads() method which converts JSON String to Python dictionary

_jsondata  = "{"name":"File.mp3","size":"25Mb","section":[1,2,3,4],"updateby":[{"name":"user one","date":"10:00 21 May","userrole":["add","update","delete"]},{"name":"user two","date":"10:00 21 May","userrole":["add","delete"]}],"Metadata":{"create":"21 MAy","audio":"acc","video":"H264"}}";

// parse string in JSON Object
jsonData = json.loads(_jsondata)

STEP 2: To identify data types, We can use the isinstance() method. It will return true if the type matches.

//To Identify String
isinstance(jsonData[keys], str)

//To Identify Object
isinstance(jsonData[keys], dict)

STEP 3: To read all the keys, we can initialize any control flow statement to extract data from Python Object.

for keys in jsonData:
...

Let’s see a complete code of parse JSON data in Python:

import json

def JsonParserInPython(jsonData):
    """
    Parse JSON String in python
    """
    print("Let's Parse JSON in Python")
    try:
        #Let's Find all keys
        for keys in jsonData:
            print("Key : ",keys, " | Value :", jsonData[keys])
            if isinstance(jsonData[keys], list):
                print(" Value is array.")
                #array iterator with index in python
                for idx, array in enumerate(jsonData[keys]):
                    print(" Index : ", idx," | Value : ", array)
                print(" ")
            if isinstance(jsonData[keys], dict):
                print(" Value is JSON Object.")
            if isinstance(jsonData[keys], str):
                print(" Value is string.")
            if isinstance(jsonData[keys], int):
                print(" Value is integer.")

        return
    except Exception as err:
        print("The err thrown while excuting the code", err)
        return

Download


Source Code : Click here

Credits


Python Doc - CPP JSON encoders/decoders library

json.org - Introducing JSON Standard