Python – JSON

After reading this Python JSON topic, you will understand how to convert JSON to Python Object, Python Object to JSON String, theory, and examples in Python.

JSON stands for JavaScript Object Notation. JSON is a standard text used for exchanging data between server and client. Python has a built-in package named as json which support encoding and decoding of json using python.

How to Import JSON object?

Before start working with json in python, first you need to import json package using the statement in python as

import json

using import keyword, we can start work with json in python.

JSON to Python Object

For converting json string to python object use json.loads() method.

Example:

Program (1): To show how to convert json to python object in Python.

import json
# json string
x='{"cricket":1, "football":2, "hockey":3}'
# using json.loads(x) method
y = json.loads(x)
# the result is a Python dictionary:
print(y["hockey"])

Output(1)

3

Converting JSON String to Python Object

The Python object can be either a dictionary, list, tuple, string, integer, float, etc. For converting python object to json string use json.loads() method.

Example:

Program (1): To show how to convert json string to a dictionary in Python.

import json
# creating json string
x='{"cricket":1, "football":2, "hockey":3}'
# using json.loads(x) method
y = json.loads(x)
# display Python dictionary
print(y)

Output(1)

{'cricket': 1, 'football': 2, 'hockey': 3}

Program (2): To show how to convert json string to list in Python.

import json
# creating json string
x='["cricket", "football", "hockey"]'
# using json.loads(x) method
y = json.loads(x)
# display Python list
print(y)

Output(2)

['cricket', 'football', 'hockey']

Converting Python Object to JSON String

The Python object can be either dictionary, list, tuple, string, integer, float, etc. For converting python object to json object use json.dumps(x) method.

Examples:

Program (1): To show how to convert the dictionary to json string in Python.

import json
# Python object as dictionary
x={'cricket': 1, 'football': 2, 'hockey': 3}
# using json.dumpss(x) method
y = json.dumps(x)
# display json string
print(y)

Output(1)

{“cricket”: 1, “football”: 2, “hockey”: 3}

Program (2): To show how to convert tuple to json string in Python.

import json
# Python object as tuple
x= ('cricket', 'football', 'hockey')
# using json.dumpss(x) method
y = json.dumps(x)
# display jsonstring
print(y)

Output(2)

["cricket", "football", "hockey"]

Program (3): To show how to convert a list to json string in Python.

import json
# Python object as List
x= ['cricket', 'football', 'hockey']
# using json.dumpss(x) method
y = json.dumps(x)
# display json string
print(y)

Output(3)

["cricket", "football", "hockey"]

Published by

Electrical Workbook

We provide tutoring in Electrical Engineering.

Leave a Reply

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