JSON in Python

JSON in Python

JSON in Python is used to send data from python programs by converting them in JSON format to the server and then converted back into original format from JSON format by retrieving it from the the server. JSON stands for JavaScript Object Notation. It is a language independent data-format used for storing and transmitting data. This data-format can be easily sent to and from the server and used by any programming language by converting it into appropriate acceptable data-formats.

The table given below is the list of Python objects that can be converted into equivalent JSON objects:

 

Python Objects JSON equivalent
dict Object
list Array
tuple Array
str String
int Number
float Number
True true
False false
None null

 

 

Parse JSON

JSON data can be converted into object like dictionary with the help of functions defined in the module named “json”. This module can be imported in the current script using the import statement. load() method is then used to convert JSON into dictionary type data.

Example:

 

# Python program to exemplify JSON parsing into a Python object

import json

# JSON data
json_data =  '{ "name":"Skylar", "age":18, "city":"London"}'

# parse json_data
Dict = json.loads(json_data)

# the result is a Python dictionary:
print(Dict)

In the program provided above, json module is imported and a JSON object is created. loads() method of the json module is then used to convert it into a dictionary. In the end, it is printed to the console.

Output:

{'name': 'Skylar', 'age': 18, 'city': 'London'}

 

 

Convert Python to JSON

Python object can be converted into JSON using the json module. More specifically, using the dumps() method of the module.

Example:

 

# Python program to exemplify conversion of Python object into JSON
import json

#Create a Python dictionary
Dict = {
  "name":"Skylar",
  "age":18,
  "city":"London"
}

#convert Python dictionary into JSON
json_data =  json.dumps(Dict)

#the result is a JSON object:
print(json_data)

In the program provided above, json module is imported. A dictionary is created with three key-value pairs and is then passed to the method dumps() to convert it into a JSON object. In the end, it is printed to the console.

Output:

{"name": "Skylar", "age": 18, "city": "London"}

 

 

Writing JSON to a File

To write JSON to a file, dumps() method of the json module is used.

Example:

 

# Python program to exemplify writing JSON to a file
import json

# Create a Python dictionary
Dict = {
  "name":"Skylar",
  "age":18,
  "city":"London"
}

with open('test.txt', 'w') as json_file:
  json.dump(Dict, json_file)

File = open("test.txt", "r")
# Read content of the file
print(File.readlines())

In the program provided above, json module is imported along with a dictionary with three key-value pairs. 

Output:

['{"name": "Skylar", "age": 18, "city": "London"}']

 

 

Share this post

Leave a Reply

Your email address will not be published.