Python JSON

This is a detailed guide on Python JSON. Learn to fetch data from existing JSON Files or to create one yourself by dumping some data into it.

JSON Files

JSON (JavaScript Object Notation) is one of the common ways to store and exchange data over the Internet. A lot of software and web applications make use of JSON for data exchange. Even for CRUD API Operations, API exchange data in the JSON form. A JSON file stores the data in the form of key-value pairs that can even be nested like a JavaScript Object. You can find more about JSON here.

The following screenshot shows a sample file containing some JSON data.

JSON Example

As I mentioned JSON files can contain nested data i.e. another set of key-value pair data inside as the value of a particular key and the above-displayed JSON file also illustrates the concept of nested key-value pair data.

Therefore, JSON Data is similar to Python Dictionary.

Handling JSON Data in Python

Python has got an inbuilt module named json which can be used to process the JSON data. This module can be imported into your python program file and then its different methods can be used to either parse a JSON file to fetch the data from it or to dump some data into a JSON file.

Converting JSON File To Python Dictionary (Parsing JSON Data)

As I already mentioned, JSON Data is similar to Python Dictionary Data Type, therefore, we can parse the JSON File and convert it directly into a Python Dictionary using the json.loads() method.

Example. The following python code illustrates how you can convert JSON to Python Dictionary.

import json

#Example JSON String
jsonData = '{"id" : 45, "bio" : {"name" : "Gurmeet Singh", "age" : 21}, "state" : "Punjab"}'

#JSON String to Python Dictionary Conversion
pythonDict = json.loads(jsonData)

print(jsonData)

#Fetching Particular Value(s) using Key
print(pythonDict['bio']['name'])
print(pythonDict['state'])

Observe the code carefully. We’ve provided the JSON Data as a Python String and then we’ve used the json.loads() method by passing the argument as the JSON string variable. This way, the method returns us a dictionary and now we can fetch the values using the square bracket notation by making use of the keys.

JSON To Python Example

Creating Python Data To JSON

If you have a python object containing some data, you can convert it into a JSON string using the json.dumps() method. As we have learned that the JSON Strings are being converted into Python Dictionaries using the json.loads() method. But you can convert multiple python objects into a JSON string and not just the dictionary.

Example. The following python code illustrates the conversion of a python dictionary into a JSON String.

import json

#A Python Dictionary
pythonDict = {
    "id" : 45,
    "bio" : {
        "name" : "Gurmeet Singh",
        "age" : 21
    },
    "state" : "Punjab"
}

#Converting Python Dictionary To JSON
jsonString = json.dumps(pythonDict)

print(jsonString)

Here I’ve defined a dictionary and stored it as the variable pythonDict, then I have passed this variable as the argument to the json.dumps() method and it returns us a JSON string formed using the dictionary data.

Python To JSON Example

Note. As already mentioned you can also convert other Python Objects into a JSON string. The data types that can be converted into JSON are listed below.

  • Dictionary
  • List
  • Tuple
  • String
  • Integer
  • Float
  • Boolean (True, False)
  • None

JSON is usually meant to be read in your JavaScript Code. Therefore, when you convert the above-listed data types, it converts into the following of their JavaScript equivalents.

  • Dictionary to JavaScript Object
  • List to JavaScript Array
  • Tuple to JavaScript Array
  • String to String
  • Integer to Number
  • Float to Number
  • Boolean (True, False) to Boolean (true, false)
  • None to null

Example. Here we’re converting the above-specified python data types into JSON. We’ve already illustrated the dictionary to JSON conversion, so this example illustrates the conversion of other python data types.

import json

#Different Python Data Type Objects
aList = ["Gurmeet Singh", 21, "Punjab"]
aTuple = ("Gurmeet Singh", 21, "Ludhiana")
aString = "Hello!"
aInteger = 5
aFloat = 12.45
aTrue = True
aFalse = False
aNull = None

#Converting all into JSON
print(json.dumps(aList))
print(json.dumps(aTuple))
print(json.dumps(aString))
print(json.dumps(aInteger))
print(json.dumps(aFloat))
print(json.dumps(aTrue))
print(json.dumps(aFalse))
print(json.dumps(aNull))

Different Python Data Type Objects To JSON Example

Example. Here we’re converting a dictionary further containing data in different Python data types into JSON.

import json

aDict = {
    "name" : "Gurmeet Singh",
    "age" : 21,
    "score" : 99.55,
    "isSelected" : True,
    "anotherTestRequired" : False,
    "otherRequirements" : None,
    "categories" : ("Programming","Digital Marketing"),
    "languages" : ["Python", "PHP", "JAVA"],
    "homeTown" : {
        "city" : "Ludhiana",
        "state" : "Punjab"
    }
}

print(json.dumps(aDict))

Python Dictionary Containing Different Data Types Converted To JSON Example

You can clearly observe in the output that the different python data types are converted into their Javascript equivalents in the JSON String. For a quick view, you can clearly see that None has been converted into its JavaScript equivalent null in the JSON string for the value of the key otherRequirements.

Formatting JSON Data

In the above example, you can clearly see that the JSON string in the output is not pretty readable because it is not well-formatted. The json module allows you to do the formatting of your JSON string by giving proper indentations and it also allows you to specify custom separator symbols for even better formatting.

Indentation

You can use the indent parameter inside the json.dumps() method to specify the required number of indents. It is an integer parameter.

Separators

Likewise, the separators parameter can also be used inside the json.dumps() method to specify the custom separator symbols. It is a Python Tuple Parameter.  The tuple further needs to have two symbols specified as a string as the tuple’s first and second items. The default separator symbols are colons and commas. A Colon separated a key and value and a comma separates the different key-value pairs by default. We’re talking about changing these symbols to our custom-specified symbols.

Example. In the following python code snippet, we’re setting the indent numbers to 5 and then changing the default separator symbols.

import json

data = {
    "name" : "Gurmeet Singh",
    "age" : 21,
    "score" : 99.55,
    "isSelected" : True,
    "anotherTestRequired" : False,
    "otherRequirements" : None,
    "categories" : ("Programming","Digital Marketing"),
    "languages" : ["Python", "PHP", "JAVA"],
    "homeTown" : {
        "city" : "Ludhiana",
        "state" : "Punjab"
    }
}

print(json.dumps(data, indent = 5, separators = (' & ', ' = ')))

In the following output, you can clearly see the indent difference and the symbol = instead of a colon and symbol & instead of a comma.

Python JSON Formatting Example

Ordering JSON Data

The json.dumps() method also allows you to sort and order the JSON Data according to the keys using a parameter named as sort_keys. It is a boolean parameter, so you just need to specify its value as True, if you want to order the JSON data and False, if not.

Example. Here we’re dumping the JSON data in the alphabetical order of the keys.

import json

data = {
    "name" : "Gurmeet Singh",
    "age" : 21,
    "score" : 99.55,
    "isSelected" : True,
    "anotherTestRequired" : False,
    "otherRequirements" : None,
    "categories" : ("Programming","Digital Marketing"),
    "languages" : ["Python", "PHP", "JAVA"],
    "homeTown" : {
        "city" : "Ludhiana",
        "state" : "Punjab"
    }
}

print(json.dumps(data, sort_keys = True))

You can clearly see in the output screenshot that the JSON data has been sorted according to the alphabetical order of the keys.

Python JSON Ordering (Alphabetical Sorting) Example

Leave a Reply

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