JSON with Python


Before we get started with how to use JSON with Python, we’ll take a look at “Table of contents?”.



The JSON stands for JavaScript Object Notation.  The JSON is a standard format that is used for storing and exchanging data. It has data stored in the form of a key-value pair. Using JSON with python, we can generate and store data in JSON files. The JSON files are stored with the extension .json.


  • JSON is a subset of JavaScript and it is something like an interpreter/translator that makes it super easy for both humans and machines to read data.
  • It’s much more compact/lightweight compared to other file formats like XML.
  • In short, JSON is a web parser that reduces the size of data or to be precise, converts them into a lightweight format.

Note: ‘YAML’ is a superset of JSON and it allows users to comment while the same does not hold true for JSON.


Download our notes on JSON with Python

JSON with Python-1Download
JSON-with-Python-2Download

Why JSON?

The reason is simple if there are better alternatives to XML, why not go for it? There is one more reason people prefer JSON. The syntax and semantics are very similar to that of Python and C, we’ll come to that asap.


Where do we need JSON?

This can be pretty much used in situations where we need to store and transmit ‘structured’ data. Most commonly used in web applications to send the data from your server to the web browser.


Now, we know the ‘what, why, where’ of JSON, so let’s take a look at the example to know more about how to use it.

JSON data

{
    "Name": "Alex",
    "Pet name": "Al",
    "Sports": ["Athlete", "Swimmer", "Football player"],
    "age": 22,
    "Parent": [{ "Name": "Alice", "age": 44},{"Name": "Jason", "age": 48}]
}

Does this Syntax look Familiar?

You are right, JSON is very similar to Python Dictionaries. The only difference we need to make is to pass it as a string. So now it’s clear that the data in JSON is in NAME: VALUE  pair which is similar to the dictionary’s KEY: VALUE pair.



Now we know how the JSON data looks like, let’s see how to use them with Python.

Note: Python has a built-in package called json to work with JSON data.

Syntax

import json

You can also import the requests module along with the json module. The requests module is used to extract the contents from the browser. In this case if the json file is heavy weighted.

Syntax

import requests

Before proceeding to the next step, there’s something we need to know. i.e. Encoding (referred to as ‘Serialization’) and Decoding (referred to as ‘Deserialization’)

Let’s try to understand these in a more elaborated manner.

We use ‘Serialization’ to convert Python objects to JSON accordingly. When encoding the Python objects, it gets converted to the JSON equivalent.

While, Deserialization‘ is used to to convert JSON to Python Objects.


Parsing JSON With Python


The loads() method is used to parse the JSON in python. Once the JSON file is parsed, it is stored in the form of dictionary.

Example

import json
# some json data
json_data = '{"name":"Jenny","age":25,"profession":"developer"}'
dic_data = json.loads(json_data)
print(dic_data[“age”])

Output

25

Converting to JSON


To convert the data into JSON format in python, we use the dumps() method. To convert into JSON, the data must be in JSON strings.

Example

import json
dic_data = '{"name":"Jenny","age":25,"profession":"developer"}' 
json_data = json.dumps(dic_data)	
print(json_data)

Output

‘{“name” : “Jenny” , “age”:”25” , “profession” : “developer”}’

JSON Strings


  • Dict – the dictionary is converted as a JSON object i.e. the dictionary itself is in the form of JSON
  • List – the list is stored in the form of arrays in JSON
  • Tuple – similar to a list, tuples are also stored in the form of arrays in JSON
  • String – stored as a string similar to that in python
  • Int – stored as a number in JSON
  • Float – stored as a number in JSON
  • Boolean – similar to that in python i.e. true or false
  • None – stored as a null value in JSON

JSONPython Objects
objectdict
arraylist
stringstr
number(int)int
number(real)float
trueTrue
falseFalse
nullNone

Note– The JSON file can have nested data. It can store an array of values for a specific key similar to that of a dictionary in python.

Example

import json
dic_data = {
            "name" : "Jenny",
            "age" : 25,	
            "profession" : "developer",
            "skill set" : ("C" ,"CPP", "JAVA", "PYTHON"),
            "previous experience" : None,
            "academic details" : [
                                  {"qualification" : "UG" , "score" : 7.5 },
                                  {"qualification" : "HSC" , "score" : 90}
                                  ]
            }
json_data = json.dumps(dic_data)
print(json_data)

Output

{"name": "Jenny", "age": 25, "profession": "developer", "skill set": ["C", "CPP", "JAVA", "PYTHON"], "previous experience": null, "academic details": [{"qualification": "UG", "score": 7.5}, {"qualification": "HSC", "score": 90}]}


Formatting the JSON appearance


Indentation

The output of the JSON may be looking congested. To improve the readability, the indents can be used inside the dumps() method.

Syntax

json.dumps(x, indent =value)

where,

  • x – is the object which has the JSON data stored in the form of dictionary
  • indent – used to improve the readability
  • value – the higher the value, the more indentations, and spaces are created between each key-value pairs of data.

Example

import json
dic_data = {
"name" : "Jenny",
"age" : 25,	
"profession" : "developer"}
print(json.dumps(dic_data))
print(json.dumps(dic_data, indent=2))
print(json.dumps(dic_data, indent=4))
print(json.dumps(dic_data, indent=6))

Output

{"name": "Jenny", "age": 25, "profession": "developer"}
{
  "name": "Jenny",
  "age": 25,
  "profession": "developer"
}
{
    "name": "Jenny",
    "age": 25,
    "profession": "developer"
}
{
      "name": "Jenny",
      "age": 25,
      "profession": "developer"
}

Usage of separators

By default the separators used are (, and :), but instead of them we can specify and change them to (. and =). To achieve that we use separators(), specify the change, and pass it inside the dumps() method.

Syntax

json.dumps(x, indent =value, separators(“.” , “=” ))

where, 

  • x – is the object which has the JSON data stored in the form of dictionary
  • indent – used to improve the readability
  • value – the higher the value, the more indentations, and spaces are created between each key-value pairs of data.
  • separators( “.”,”=”) – the separators that need to be used instead of the default ones. Always we need to pass the separators inside the quotes.

Example

import json
dic_data = {
"name" : "Jenny",
"age" : 25,	
"profession" : "developer"}
print(json.dumps(dic_data, indent=3,separators=(". ", " = ")))

Output

{
   "name" = "Jenny". 
   "age" = 25. 
   "profession" = "developer"
}

Sorting the resulting data

To sort the resultant data, use the sort_keys parameter in the dumps() method. The sort_keys value can be True or False based on the requirement of the user.

Syntax

json.dumps(x, indent =value, sort_keys=bvalue)

where,             

  • x – is the object which has the JSON data stored in the form of dictionary.
  • indent – used to improve the readability.
  • value – the higher the value, the more indentations, and spaces are created between each key-value pairs of data.
  • sort_keys – parameter to indicate whether to sort the resultant data or not.
  • bvalue – the value for sort_keys. It can be of Boolean type .i.e either True or False.

Example

import json
dic_data = {
"name" : "Jenny",
"age" : 25,	
"profession" : "developer"}
print(json.dumps(dic_data, indent=3, sort_keys=True))

Output

{
   "age": 25,
   "name": "Jenny",
   "profession": "developer"
}
}

Keypoints

  1. json.loads(data) takes a string, bytes, or byte array instance which contains the JSON and returns a Python object.
  2. json.dumps(data) takes a string, bytes, or byte array instance which contains the JSON and returns a Python object.

During Dumping, you can pass the inputs as lists, dictionaries, strings, and many more python objects. So feel free to play around with them.