Page Contents
What is JSON?
JSON (JavaScript Object Notation) is a lightweight data interchange format that’s easy for humans to read and write, and easy for machines to parse and generate. Python has a built-in module called json that can be used to work with JSON data.
Let’s begin with a basic example and convert a JSON string to a Dictionary:
# Import json module.
import json
data = '{"name": "Shivaay Singh Chauhan", "age": 6, "city": "Haridwar"}'
# Loading a JSON data as a Dictionary.
data_dict = json.loads(data)
# iterating over the dictionary items and printing key, value pairs.
for key, value in data_dict.items():
print(key, "=", value)
# Output
name = Shivaay Singh Chauhan
age = 6
city = Haridwar
In this example, we have loaded a JSON string to a python dictionary. Let’s see how to convert a python dictionary to a JSON string.
# Python Dictionary to a JSON string.
data = {
"name": "Shivaay Singh Chauhan",
"age": 6,
"city": "Haridwar"
}
dict_json = json.dumps(data)
print("dict to json: ", dict_json)
#Output
dict to json: {"name": "Shivaay Singh Chauhan", "age": 6, "city": "Haridwar"}
Reading JSON from a file
To read JSON data from a file and convert it into a Python dictionary, you can use the json.load() method.
demo.json file:
{
"name": "Shivaay Singh Chauhan",
"age": 6,
"city": "Haridwar"
}
Python Code:
import json
data = {}
with open("demo.json","r") as file:
data = json.load(file)
print(data)
print(type(data))
# Output
{'name': 'Shivaay Singh Chauhan', 'age': 6, 'city': 'Haridwar'}
<class 'dict'>
Writing JSON to a File
To write a Python dictionary to a file in JSON format, you can use the json.dump() method.
import json
person_dict = {"name": "Shivaay Singh Chauhan",
"languages": ["Hindi", "English"],
"married": False,
"age": 6
}
with open("person.txt", "w") as json_file:
json.dump(person_dict, json_file)
Pretty Printing JSON
To pretty print a JSON string, you can use the indent parameter in the json.dumps() method.
- You can use the
indentparameter to define the numbers of indents. - You can separators, default value is (“, “, “: “), which means using a comma and a space to separate each object, and a colon and a space to separate key and value.
# Python Dictionary to a JSON string.
data = {
"name": "Shivaay Singh Chauhan",
"age": 6,
"city": "Haridwar"
}
# Use the indent parameter to define the numbers of indents.
dict_json = json.dumps(data, indent=4, separators=("$ ", " :: "))
print("dict json: ", dict_json)
# Output
dict json: {
"name" :: "Shivaay Singh Chauhan"$
"age" :: 6$
"city" :: "Haridwar"
}
You can also sort the result by using `sort_keys` paramter:
# Python Dictionary to a JSON string.
data = {
"name": "Shivaay Singh Chauhan",
"age": 6,
"city": "Haridwar"
}
# Use the indent parameter to define the numbers of indents.
dict_json = json.dumps(data, indent=4, separators=("$ ", " :: "), sort_keys=True)
print("dict json: ", dict_json)
# Output
dict json: {
"name" :: "Shivaay Singh Chauhan"$
"age" :: 6$
"city" :: "Haridwar"
}
# Output
dict json: {
"age" :: 6$
"city" :: "Haridwar"$
"name" :: "Shivaay Singh Chauhan"
}
Using custom serializer for complex data-types
import json
from datetime import datetime
# Custom serializer for complex data-types like datetime.
def custom_serializer(value):
if isinstance(value, datetime):
# Converting a datetime into string ISO 8601 format.
return value.isoformat()
raise TypeError("Value is not Serializable.")
# the key joined has a value of type 'datetime.datetime'.
data = {
"name": "John",
"age": 30,
"joined": datetime.now()
}
json_string = json.dumps(data, default=custom_serializer)
print(json_string)
# Output
{"name": "John", "age": 30, "joined": "2024-06-16T19:49:02.535075"}