Python – JSON
In this tutorial, we will learn python in detail.
JSON full form is JavaScript Object Notation which is used to store and exchange data. It is a lightweight data interchange format inspired by JavaScript object literal syntax. It is written with JavaScript object notation and is a text. To work with JSON data, python has to import package called json.
Initially we import the json package in Python script to work on it.
import json
Now let us look at json file and how it looks like.
{
"firstName": "Jane",
"lastName": "Doe",
"hobbies": ["running", "sky diving", "singing"],
"age": 35,
"children": [
{
"firstName": "Alice",
"age": 6
},
{
"firstName": "Bob",
"age": 8
}
]
}
JSON supports strings, numbers as well as nested lists and objects.
Convert from JSON to Python
The conversion process is fairly equivalent. Below table shows how JSON objects are converted into Python objects.
JSON | PYTHON |
object | dict |
array | list |
string | str |
number (int) | int |
number (real) | float |
true | True |
false | False |
null | None |
- Using json.loads()
Sometimes we need to convert JSON string into a Python dictionary. json.loads() method is used to deserialize into python dictionary.
Example:
import json
# some JSON:
x = '{ "name":"John", "age":30, "city":"New York"}'
# parse x:
y = json.loads(x)
# the result is a Python dictionary:
print(y["age"])
Output:
30
- Using Json.load()
This method is used to read JSON data from a file and convert it into dictionary. Future we use this dictionary to access and manipulate data in our application.
Let’s see an example
Here we have a file named data.json. This file contains the following data.
{
"emp_details": [
{
"emp_name": "Shubham",
"email": Shubham@gmail.com,
"job": "intern"
},
{
"emp_name": "Laxmi",
"email": Laxmi@gmail.com,
"job": "developer"
}
]
}
Below is the implementation to read the content of this file.
import json
print("Started Reading JSON file")
with open("data.json", "r") as read_file:
print("Converting JSON encoded data into Python dictionary")
emp = json.load(read_file)
print("Decoded JSON Data From File")
for i in emp(‘emp_details’):
print(i)
print("Done reading json file")
Output:
Started Reading JSON file
Converting JSON encoded data into Python dictionary
Decoded JSON Data From File
{‘emp_name’: ‘Shubham’, ‘email’: ‘Shubham@gmail.com’, ‘job’: ‘intern’}
{‘emp_name’: ‘Laxmi’, ‘email’: ‘Laxmi@gmail.com’, ‘job’: ‘developer’}
Convert from Python to JSON
Obviously, Serialization is the reciprocal process of deserialization i.e., encoding JSON. Python objects are converted to JSON according to a fairly equivalent conversion. Below table shows the conversion process.
Python | JSON |
dict | Object |
list | Array |
tuple | Array |
Str | String |
int | Number |
float | Number |
True | true |
False | false |
None | null |
You can convert a Python object it into a JSON string by using the json.dumps() method. Whereas json.dump() method converts data into json file.
Example:
import json
x = {
"name": "John",
"age": 30,
"married": True,
"divorced": False,
"children": ("Ann","Billy"),
"pets": None,
"cars": [
{"model": "BMW 230", "mpg": 27.5},
{"model": "Ford Edge", "mpg": 24.1}
]
}
print(json.dumps(x))
Output:
{"name": "John", "age": 30, "married": true, "divorced": false, "children": ["Ann","Billy"], "pets": null, "cars": [{"model": "BMW 230", "mpg": 27.5}, {"model": "Ford Edge", "mpg": 24.1}]}
The above example looks clumsy and it is not easy to read with no indentations and line breaks.
By using indent parameter, we can define the number of indents. Below code uses indent parameter.
Example:
Print(json.dumps(x, indent=4))
Output:
{
"name": "John",
"age": 30,
"married": true,
"divorced": false,
"children": [
"Ann",
"Billy"
],
"pets": null,
"cars": [
{
"model": "BMW 230",
"mpg": 27.5
},
{
"model": "Ford Edge",
"mpg": 24.1
}
]
}
Use the ‘separators’ parameter to change the default separator.
Example:
Print(json.dumps(x, indent=4, separators=(". ", " = ")))
Output:
{
"name" = "John".
"age" = 30.
"married" = true.
"divorced" = false.
"children" = [
"Ann".
"Billy"
],
"pets" = null.
"cars" = [
{
"model" = "BMW 230".
"mpg" = 27.5
}.
{
"model" = "Ford Edge".
"mpg" = 24.1
}
]
}
Using sort_keys parameter to sort the result alphabetically.
Example:
Print(json.dumps(x, indent=4, sort_keys=True))
Output:
{
“age”: 30,
“cars”: [
{
“model”: “BMW 230”,
“mpg”: 27.5
},
{
“model”: “Ford Edge”,
“mpg”: 24.1
}
],
“children”: [
“Ann”,
“Billy”
],
“divorced”: false,
“married”: true,
“name”: “John”,
“pets”: null
}
So, we have gone through,
- Import the json package.
- Read the data with load() or loads().
- Process the data.
- Write the altered data with dump() or dumps()