Python JSON

JSON (JavaScript Object Notation) is a language-independent data format used to store or represent structured data. It is common to send and receive data in JSON format between a server and a web application. Python has a built-in package called JSON that supports JSON. To use this functionality, we must first import the JSON package into our Python program.

JSON exists in Python as a string. For example:

p = ‘{“name”: “Bob”, “languages”: [“Python”, “Java”]}’

# Import the JSON module:

import json

Write JSON to a File

After importing the JSON Python module, you can write JSON onto a file. The package provides a method called json.dump() that allows writing JSON to a file.

The json.dump() method accepts two arguments:

  • Dictionary: Name of the dictionary
  • File pointer: File pointer in open or append mode

We’ll create a file named example.json and convert a dictionary into a JSON object using the json.dumps() method. 

import json

# Initializing dictionary

dic_exm ={

“name” : “Usman”,

“roll_no” : 1,

“cgpa” : 3.5,

“phone_num” : “03001234567”

}

with open(“example.json”, “w”) as outfile:

json.dump(dic_exm, outfile)

Output:

# File name example.json

{“Name” : “Usman”, “roll_no” : 1, “cgpa” : 3.5, “phone_num” : “03001234567”}

Convert From JSON to Python (Parse JSON)

json.load() method can be used to parse a valid JSON string and convert it into a Python dictionary.

Example 1:

import json 

# JSON string 

employee = ‘{“id” : ”10”, “name” : “Usama”, “department” : “IT”}’

print(“This is JSON”, type(employee)) 

print(“\nNow convert from JSON to Python\n”) 

# Convert string to Python dict 

employee_dict = json.loads(employee) 

print(“Converted to Python”, type(employee_dict)) 

print(employee_dict) 

Output: 

This is JSON <class ‘str’>

Now convert from JSON to Python

Converted to Python <class ‘dict’>

{‘id’: ‘10’, ‘name’: ‘Usama’, ‘department’: ‘IT’}

Example 2:

import json

# some JSON:

x = ‘{ “name” : “Shafiq”, “age” : 20, “class” : “12th”, “city” : “Lahore”}’

# parse x:

y = json.loads(x)

# the result is a Python dictionary:

print(y[“name”])

print(y)

Output:

Shafiq

{‘name’: ‘Shafiq’, ‘age’: 20, ‘class’: ‘12th’, ‘city’: ‘Lahore’}

With the JSON Python, you can convert the following Python objects to JSON strings:

dict list tuple str int float True False None

The code uses the Python objects and converts them to JSON using the .dumps() method from the JSON Python package.

# Convert Python to JSON

print(json.dumps({“name”: “Ibrar”, “age”: 30}))

Output: {“name”: “Ibrar”, “age”: 30}

# Convert List to Array

print(json.dumps((“Fruits”, “Juice”)))

Output: [“Fruite”, “Juice”]

# Convert Tuple to Array

print(json.dumps(“Hello Python!”))

Output: Hello Python!

# Convert Int to Number

print(json.dumps(55.8))

Output: 55.8

# Convert False to false

print(json.dumps(False))

Output: false

Convert from Python to JSON

Similar to json.dump() method, the json Python also provides json.dumps() method. The only difference between the two is that json.dumps() converts a dictionary to a JSON object and json.dump() writes a JSON to file without the conversion. The json.dumps() method accepts the following two arguments:

  • Dictionary: Name of the dictionary
  • Indent: Number of units for indentations

Example 1:

For this example, you will use the same example that was used while learning the json.dump() method but this time with the json.dumps() method.

import json

import json

# Initializing dictionary

dic_exm ={

“name” : “Usman”,

“roll_no” : 1,

“cgpa” : 3.5,

“phone_num” : “03001234567”

}

# Serializing json

json_obj = json.dumps(dic_exm, indent = 4)

# Writing to sample.json

with open(“example.json”, “w”) as outfile:

outfile.write(json_obj)

Output:

{

“roll_no”: 1,

“Cgpa”: 3.5,

“phone_num”: “03001234567”,

“name”: “Usman”,

}

Example 2:

import json

# a Python object (dict):

x = {

  “name”: “Haider”,

  “age”: 30,

  “city”: “Karachi”

}

# convert into JSON:

y = json.dumps(x)

# the result is a JSON string:

print(y)

Output:

{“name”: “Haider”, “age”: 30, “city”: “Karachi”}

Convert a Python object containing all the legal data types:

import json

x = {

  “name” : “Arslan”,

  “age” : 35,

  “married” : True,

  “divorced” : False,

  “children” : (“Asad”, “Bilal”),

  “pets” : None,

  “cars” : [

    {“model” : “Honda City”, “mpg”: 23.5},

    {“model” : “Toyota Corolla”, “mpg”: 20.1}

  ]

}

# convert into JSON:

y = json.dumps(x)

# the result is a JSON string:

print(y)

Output:

{“name”: “Arslan”, “age”: 35, “married”: true, “divorced”: false, “children”: [“Asad”, “Bilal”], “pets”: null, “cars”: [{“model”: “Honda City”, “mpg”: 23.5}, {“model”: “Toyota Corolla”, “mpg”: 20.1}]}

Format the Result

The json.dumps() method has parameters to make it easier to read the result:

Example

Use the indent parameter to define the numbers of indents:

import json

x = {

  “name” : “Haider”,

  “age” : 30,

  “city” : “Karachi”

}

# use four indents to make it easier to read the result:

print(json.dumps(x, indent=4))

Output:

{

“name”: “Haider”,

“age”: 30,

“city”: “Karachi”

}

Use the separators parameter to change the default separator:

import json

x = {

  “name” : “Haider”,

  “age” : 30,

  “city” : “Karachi”

}

# use . and a space to separate objects, and a space, a = and a space to separate keys from their values:

print(json.dumps(x, indent=4, separators=(“. “, “ = “)))

Output:

{

“name” = “Haider”. 

“age” = 30. 

“city” = “Karachi”

}

Order the Result

Use the sort_keys parameter to specify if the result should be sorted or not:

import json

x = {

  “name” : “Haider”,

  “age” : 30,

  “city” : “Karachi”

}

# sort the result alphabetically by keys:

print(json.dumps(x, indent=4, sort_keys=True))

Output:

{

“age”: 30,

“city”: “Karachi”,

“name”: “Haider”

}

Conclusion:

You have learned everything about the JSON Python package. You have also seen how to convert JSON to Python and vice versa with various examples. You can store and transfer data between the servers and your Python web application more easily if you are well-versed in JSON Python.

Visited 2 times, 1 visit(s) today