In this tutorial, you will learn how to read JSON formatted strings, read JSON files as well as write in files and convert JSON objects into Python objects.
A very common task performed by many programmers is parsing JSON – that stands for JavaScript Object Notation – files.
This format is lightweight, especially when compared to XML, and the most common way to interact with API’s.
As such, all major languages have some way to consume JSON files, and in Python this is very simple and straightforward.
Let’s see how to work with JSON with the following examples, which are:
- Reading JSON formatted string
- Converting Python object to JSON
- Writing in a file after converting from Python object to JSON
- Reading the file with content in JSON and turning it back to a Python object
- Format the output, so it is easier to understand
Reading JSON
Python has a builtin module to take care of JSON files for us, to use it we simply import it like so:
import json
Let’s create a string called car_json with some data about the car BMW 320i, as you can see, the string is formatted as JSON.
car_json = '{"name": "BMW 320i", "car body": ["4-doors", "sedan"]}'
Finally, to convert the JSON data to a Python object, we use the loads(s) method to will deserialize the parameter as shown below.
bmw = json.loads(car_json)
print(bmw)
#output:
#{'car body': ['4-doors', 'sedan'], 'name': 'BMW 320i'}
print(bmw['car body'])
#output:
#['4-doors', 'sedan']
Please notice the use of loads(s) instead of load(fp). This second one, load(fp), is used to work with files, as I will show later.
Converting Python object to JSON
To do the opposite, turn a Python object into a JSON is also very straightforward.
Import the json module:
import json
Initialize a Python object with some data:
bmw = {
"name": "BMW 320i",
"torque": "300 Nm",
"year": 2019,
"top speed": "240 km",
"cylinder capacity": "1998 cc"
}
Use the dumps(obj) to serialize obj to a JSON formatted string. After that, I just print the result.
car_json = json.dumps(bmw)
print(car_json)
#output:
#{"cylinder capacity": "1998 cc", "torque": "300 Nm", "name": "BMW 320i", "top speed": "240 km", "year": 2019}
Please notice the use of dumps(s) instead of dump(fp). This second one, dump(fp), is used to work with files, as I will show later.
Writing JSON file
Import the json module:
import json
Initialize the bmw object:
bmw = {
"name": "BMW 320i",
"torque": "300 Nm",
"year": 2019,
"top speed": "240 km",
"cylinder capacity": "1998 cc"
}
Write a regular file in disk using the dump(obj) method:
with open('bmw.json', 'w') as car_json:
json.dump(bmw, car_json)
Check if the file bmw.json was created in the same folder where the program was executed.
Notice the use of dump(fp) instead of dumps(s), the dump(fp) method supports a file object.
Reading JSON file
To read the file you just created, as usual, first import the module:
import json
Open the file as you would do with any regular file and load the json, converting it to a Python object:
with open('bmw.json', 'r') as car_json:
bmw_from_file = json.load(car_json)
Then, print the object:
print(bmw_from_file)
#output:
#{'year': 2019, 'cylinder capacity': '1998 cc', 'torque': '300 Nm', 'name': 'BMW 320i', 'top speed': '240 km'}
Please notice the use of load(fp) instead of loads(s), the load(fp) method supports a file object.
Format the output
Finally, to make the output more readable, in the console or in the file, we can specify the number of indents and a sorting parameter.
print(json.dumps(bmw_from_file, indent = 4, sort_keys=True))
#output
#{
# "cylinder capacity": "1998 cc",
# "name": "BMW 320i",
# "top speed": "240 km",
# "torque": "300 Nm",
# "year": 2019
#}
You can see a pretty print as a result.
A very common task performed by many programmers is parsing JSON – that stands for JavaScript Object Notation – files.
This format is lightweight, especially when compared to XML, and the most common way to interact with API’s.
As such, all major languages have some way to consume JSON files, and in Python this is very simple and straightforward.
Let’s see how to work with JSON with the following examples, which are:
- Reading JSON formatted string
- Converting Python object to JSON
- Writing in a file after converting from Python object to JSON
- Reading the file with content in JSON and turning it back to a Python object
- Format the output, so it is easier to understand
Reading JSON
Python has a builtin module to take care of JSON files for us, to use it we simply import it like so:
import json
Let’s create a string called car_json with some data about the car BMW 320i, as you can see, the string is formatted as JSON.
car_json = '{"name": "BMW 320i", "car body": ["4-doors", "sedan"]}'
Finally, to convert the JSON data to a Python object, we use the loads(s) method to will deserialize the parameter as shown below.
bmw = json.loads(car_json)
print(bmw)
#output:
#{'car body': ['4-doors', 'sedan'], 'name': 'BMW 320i'}
print(bmw['car body'])
#output:
#['4-doors', 'sedan']
Please notice the use of loads(s) instead of load(fp). This second one, load(fp), is used to work with files, as I will show later.
Converting Python object to JSON
To do the opposite, turn a Python object into a JSON is also very straightforward.
Import the json module:
import json
Initialize a Python object with some data:
bmw = {
"name": "BMW 320i",
"torque": "300 Nm",
"year": 2019,
"top speed": "240 km",
"cylinder capacity": "1998 cc"
}
Use the dumps(obj) to serialize obj to a JSON formatted string. After that, I just print the result.
car_json = json.dumps(bmw)
print(car_json)
#output:
#{"cylinder capacity": "1998 cc", "torque": "300 Nm", "name": "BMW 320i", "top speed": "240 km", "year": 2019}
Please notice the use of dumps(s) instead of dump(fp). This second one, dump(fp), is used to work with files, as I will show later.
Writing JSON file
Import the json module:
import json
Initialize the bmw object:
bmw = {
"name": "BMW 320i",
"torque": "300 Nm",
"year": 2019,
"top speed": "240 km",
"cylinder capacity": "1998 cc"
}
Write a regular file in disk using the dump(obj) method:
with open('bmw.json', 'w') as car_json:
json.dump(bmw, car_json)
Check if the file bmw.json was created in the same folder where the program was executed.
Notice the use of dump(fp) instead of dumps(s), the dump(fp) method supports a file object.
Reading JSON file
To read the file you just created, as usual, first import the module:
import json
Open the file as you would do with any regular file and load the json, converting it to a Python object:
with open('bmw.json', 'r') as car_json:
bmw_from_file = json.load(car_json)
Then, print the object:
print(bmw_from_file)
#output:
#{'year': 2019, 'cylinder capacity': '1998 cc', 'torque': '300 Nm', 'name': 'BMW 320i', 'top speed': '240 km'}
Please notice the use of load(fp) instead of loads(s), the load(fp) method supports a file object.
Format the output
Finally, to make the output more readable, in the console or in the file, we can specify the number of indents and a sorting parameter.
print(json.dumps(bmw_from_file, indent = 4, sort_keys=True))
#output
#{
# "cylinder capacity": "1998 cc",
# "name": "BMW 320i",
# "top speed": "240 km",
# "torque": "300 Nm",
# "year": 2019
#}
You can see a pretty print as a result.