Read and Write JSON with Python

Introduction

JSON stands for JavaScript Object Notation (http://www.json.org) and was proposed by Douglas Crockford. JSON is an easy to understand data exchange format which is independent of programming languages.

Why JSON?

JSON allows websites to load data quickly and asynchronously in the background without much delay.

JSON doesn’t have end tags like XML, is shorter than XML and lightweight.

JSON is preferred way of exchanging data in AJAX requests and in REST architecture.

JSON data is offered by API’s hosted by Google, Facebook, Microsoft, SalesForce, Twitter, LinkedIn and others.

JSON Syntax

JSON is made up of string:value pairs. An object represents these string:value pairs. An object may contain a number of individual string:value pairs or a string may contain multiple string:value pairs (nested string:value pairs) or an array of string:value pairs (array of objects) or all of these.

An object should be enclosed within parenthesis { } and an array of objects should be enclosed within square brackets [ ]. Each string is followed by a : (colon)  and each of these string:value pairs should be separated by a comma.

An object with Individual string:value pairs

This JSON object has individual string:value pairs, separated by comma and enclosed within parenthesis { }.

{
    "FirstName":"Bhairav",
    "MiddleName":"S",
    "LastName":"Ram"
}

An object with string containing multiple string:value pairs (nested string:value pairs)

This JSON object is already enclosed within parenthesis { } and also the string “Contact” has few other nested string:value pairs.

{
    "Contact":{
        "Phone":9988776655,
        "Email":"bhairav@gmail.com"
}

An object with array of string:value pairs (array of JSON objects)

This JSON object is enclosed within parenthesis { }. The string “Address” is followed by an array of JSON objects separated by comma and enclosed within brackets [ ].

{
    "Address":[
        {
            "Type":"Office",
            "ZipNumber":560056,
            "Street":"Nagarbhavi Road",
            "City":"Bangalore",
            "Country":"India"
        },
        {
            "Type":"Home",
            "ZipNumber":560004,
            "Street":"Gandhi Bazaar Road",
            "City":"Bangalore",
            "Country":"India"
        }
    ]
}

So we came across various JSON verbs like object, string:value and array. An string should be enclosed within double quotes. A value can be a number, string, object itself, true value, false value or null value.

VerbsAs seen in below figure, JSON object starts at line-1 and ends at line-26. In line-7 a number value is assigned to string Phone. Nested string:value pairs starts from line-6 to line-9. An array of json objects starts from line-10 and ends at line-25.jsonBelow figure depicts how JSON verbs compare with Python identifiers.

jsonPy

Read JSON with Python

Here we import the package json in line-1. From line-4 to line-29, we create an JSON object. This JSON object is then converted into a string by enclosing it within quotes and is assigned to the variable input. This JSON object cannot be assigned directly to a variable, instead In line-32, we make use of the method loads in json library to convert json object into Python dictionary and assign it to a dictionary variable jsonObjectInfo. If we want to print the value of string FirstName then the code is jsonObjectInfo[‘FirstName’]. We use a for loop to loop through the array Address.

If you already have an existing json file then we can open that file using open method where f is a file handler (or TextIOWrapper) and load that file handler using open method. Here ‘r’ is the reading mode in which the file is opened. While working with a file we use the method load and not loads.

import json

input = '''
{
    "FirstName":"Bhairav",
    "MiddleName":"S",
    "LastName":"Ram",
    "DateOfBirth":"09-01-1984",
    "Contact":{
        "Phone":9988776655,
        "Email":"bhairav@gmail.com"
    },
    "Address":[
        {
            "Type":"Office",
            "ZipNumber":560056,
            "Street":"Nagarbhavi Road",
            "City":"Bangalore",
            "Country":"India"
        },
        {
            "Type":"Home",
            "ZipNumber":560004,
            "Street":"Gandhi Bazaar Road",
            "City":"Bangalore",
            "Country":"India"
        }
    ]
}
        '''
print(type(input))
jsonObjectInfo = json.loads(input)
print(type(jsonObjectInfo))
print(jsonObjectInfo)
print("First Name is {0}".format(jsonObjectInfo['FirstName']))
print("Middle Name is {0}".format(jsonObjectInfo['MiddleName']))
print("Last Name is {0}".format(jsonObjectInfo['LastName']))
print("Date of Birth is {0}".format(jsonObjectInfo['DateOfBirth']))
print("Phone Number is {0}".format(jsonObjectInfo['Contact']['Phone']))
print("Email ID is is {0}".format(jsonObjectInfo['Contact']['Email']))
print("-----------------**************---------------")
for eachJsonObject in jsonObjectInfo['Address']:
    print("Address Type is {0}".format(eachJsonObject['Type']))
    print("Zip Number is {0}".format(eachJsonObject['ZipNumber']))
    print("Street Name is {0}".format(eachJsonObject['Street']))
    print("City Name is {0}".format(eachJsonObject['City']))
    print("Country Name is {0}".format(eachJsonObject['Country']))
    print("-----------------**************---------------")


# Reading JSON data back from a file called JSONData.json
#Use the method json.load()
#It's just load and not loads()
#Decode JSON Data
with open('JSONData.json', 'r') as f:
     data = json.load(f)

print(data)
Output:
<class ‘str’>
<class ‘dict’>
{‘Address’: [{‘City’: ‘Bangalore’, ‘Street’: ‘Nagarbhavi Road’, ‘Type’: ‘Office’, ‘Country’: ‘India’, ‘ZipNumber’: 560056}, {‘City’: ‘Bangalore’, ‘Street’: ‘Gandhi Bazaar Road’, ‘Type’: ‘Home’, ‘Country’: ‘India’, ‘ZipNumber’: 560004}], ‘FirstName’: ‘Bhairav’, ‘LastName’: ‘Ram’, ‘Contact’: {‘Phone’: 9988776655, ‘Email’: ‘bhairav@gmail.com’}, ‘DateOfBirth’: ’09-01-1984′, ‘MiddleName’: ‘S’}
First Name is Bhairav
Middle Name is S
Last Name is Ram
Date of Birth is 09-01-1984
Phone Number is 9988776655
Email ID is is bhairav@gmail.com
—————–**************—————
Address Type is Office
Zip Number is 560056
Street Name is Nagarbhavi Road
City Name is Bangalore
Country Name is India
—————–**************—————
Address Type is Home
Zip Number is 560004
Street Name is Gandhi Bazaar Road
City Name is Bangalore
Country Name is India
—————–**************—————
{“FirstName”: “Bhairav”, “MiddleName”: “S”, “Address”: [{“ZipNumber”: 560056, “Street”: “Nagarbhavi Road”, “Country”: “India”, “City”: “Bangalore”, “Type”: “Office”}, {“ZipNumber”: 560004, “Street”: “Gandhi Bazaar Road”, “Country”: “India”, “City”: “Bangalore”, “Type”: “Home”}], “LastName”: “Ram”, “DateOfBirth”: “09-01-1984”, “Contact”: {“Phone”: 9988776655, “Email”: “bhairav@gmail.com”}}

Write JSON with Python

We create a Python dictionary data and is converted to JSON objects by using the method dumps from json library.

We can save the json objects into a file by using the method dump from json library. The file should be opened in write mode.

import json

data = {
    "FirstName":"Bhairav",
    "MiddleName":"S",
    "LastName":"Ram",
    "DateOfBirth":"09-01-1984",
    "Contact":{
        "Phone":9988776655,
        "Email":"bhairav@gmail.com"
    },
    "Address":[
        {
            "Type":"Office",
            "ZipNumber":560056,
            "Street":"Nagarbhavi Road",
            "City":"Bangalore",
            "Country":"India"
        },
        {
            "Type":"Home",
            "ZipNumber":560004,
            "Street":"Gandhi Bazaar Road",
            "City":"Bangalore",
            "Country":"India"
        }
    ]
}

#json.dumps() method turns a Python data structure into JSON:
jsonData = json.dumps(data)
print(jsonData)

# Writing JSON data into a file called JSONData.json
#Use the method called json.dump()
#It's just dump() and not dumps()
#Encode JSON data
with open('JSONData.json', 'w') as f:
     json.dump(jsonData, f)

Output:

{

“LastName”:”Ram”,
“Address”:[
{
“ZipNumber”:560056,
“City”:”Bangalore”,
“Country”:”India”,
“Type”:”Office”,
“Street”:”Nagarbhavi Road”
},
{
“ZipNumber”:560004,
“City”:”Bangalore”,
“Country”:”India”,
“Type”:”Home”,
“Street”:”Gandhi Bazaar Road”
}
],
“Contact”:{
“Phone”:9988776655,
“Email”:”bhairav@gmail.com”
},
“MiddleName”:”S”,
“FirstName”:”Bhairav”,
“DateOfBirth”:”09-01-1984″

}

Conclusion

The code in the article is available @ https://github.com/gowrishankarnath/JSONProcessingWithPython

Leave a Reply

Your email address will not be published. Required fields are marked *