1. What is JSON (JavaScript Object Notation)?
JSON (JavaScript Object Notation) is a data format originating from the JavaScript language. Data in JSON is mainly text, stored in pairs of attributes – values. JSON is commonly used in:
- Web development: transmitting data from server to client and vice versa.
- Configuration files: JSON can be used to store configurations and settings in applications. For example, the
settings.json
file in Visual Studio Code.
- Or simply use JSON to store data.
Below is an example of the file info.json
which stores data about the information of the website gochocit.com.
{
"domainname": "gochocit.com",
"active": true,
"numberposts": 430,
"category": ["hardware", "software", "network"],
"facebookpage": "https://www.facebook.com/gochocit",
"build": {
"language": "php",
"cms": "wordpress",
"database": "mysql"
}
}
The main notes on the JSON format are:
- JSON consists of a series of key-value pairs (also called attribute-value). And they are surrounded by curly braces {}.
- Each key-value pair has the format
"key": <value>
. Value can be any data type such as an object, list, string, number, boolean, null, etc. - Key-value pairs are separated by a comma “,” and only the last key-value pair has no comma “,” behind it.
Note: We should use indentation to make JSON clearer and easier to read.
2. Read JSON file with json module in Python
Python has a built-in module json to work with JSON. We need import json
to use this module. But first, we need to open and read the JSON file to read JSON data from the file with the json.load()
function.
import json
with open('info.json', 'r') as f:
data = json.load(f)
print(type(data))
print(data)
Result
<class 'dict'>
{'domainname': 'gochocit.com', 'active': True, 'numberposts': 360, 'category': ['hardware', 'software', 'network'], 'facebookpage': 'https://www.facebook.com/gochocit', 'build': {'language': 'php', 'cms': 'wordpress', 'database': 'mysql'}}
The json.load()
function will parse the JSON data and return a dictionary to be processed with Python. At this point, we can easily access the value of the key-value pairs in the JSON data.
import json
with open('info.json', 'r') as f:
data = json.load(f)
# access value of key-value
print(data["domainname"])
print(data["active"])
print(data["numberposts"])
print(data["category"])
print(data["facebookpage"])
print(data["build"])
category = data["category"]
build = data["build"]
print("type of category:", type(category))
print("type of build:", type(build))
Result
gochocit.com
True
360
['hardware', 'software', 'network']
https://www.facebook.com/gochocit
{'language': 'php', 'cms': 'wordpress', 'database': 'mysql'}
type of category: <class 'list'>
type of build: <class 'dict'>
If you have a JSON string, you need to use the json.loads()
function to convert it to a dictionary in Python.
import json
data_string = """
{
"domainname": "gochocit.com",
"active": true,
"numberposts": 360,
"category": ["hardware", "software", "network"],
"facebookpage": "https://www.facebook.com/gochocit",
"build": {
"language": "php",
"cms": "wordpress",
"database": "mysql"
}
}
"""
#convert json string to dictionary
data = json.loads(data_string)
# access value of key-value
print(data["domainname"])
print(data["active"])
print(data["numberposts"])
print(data["category"])
print(data["facebookpage"])
print(data["build"])
category = data["category"]
build = data["build"]
print("type of category:", type(category))
print("type of build:", type(build))
Result
gochocit.com
True
360
['hardware', 'software', 'network']
https://www.facebook.com/gochocit
{'language': 'php', 'cms': 'wordpress', 'database': 'mysql'}
type of category: <class 'list'>
type of build: <class 'dict'>
When converting from a JSON string to a dictionary in Python, we will have the data type of the value in JSON will be converted to the corresponding data type in Python. The table below summarizes the data type of value in JSON that will be converted to the corresponding data type in Python.
JSON | Python |
---|---|
object | dict |
array | list |
string | str |
number (int) | int |
number (float) | float |
true | True |
false | False |
null | None |
The conversion data type table above is also applicable when we read data from a JSON file.