Python JSON
JSON (JavaScript Object Notation) is a lightweight data-interchange format that is easy for humans to read and write, and easy for machines to parse and generate. Python provides a built-in module called json
for working with JSON data.
Importing the json
Module
To work with JSON data in Python, you need to import the json
module.
import json
Example 1: Converting Python Objects to JSON Strings
Use json.dumps()
to convert Python objects to JSON strings.
# Converting Python object to JSON string
import json
person = {
"name": "Karthick AG",
"age": 30,
"city": "Trichy",
"languages": ["Tamil", "English"]
}
person_json = json.dumps(person)
print("JSON String:", person_json)
JSON String: {"name": "Karthick AG", "age": 30, "city": "Trichy", "languages": ["Tamil", "English"]}
Example 2: Writing JSON Data to a File
Use json.dump()
to write JSON data to a file.
# Writing JSON data to a file
import json
person = {
"name": "Rohini",
"age": 25,
"city": "Chennai",
"languages": ["Tamil", "French"]
}
with open("person.json", "w") as json_file:
json.dump(person, json_file)
Output A file named person.json
is created with the JSON data.
Example 3: Reading JSON Data from a String
Use json.loads()
to parse JSON data from a string.
# Parsing JSON data from a string
import json
json_string = '{"name": "Durai", "age": 28, "city": "Madurai", "languages": ["Tamil", "Malayalam"]}'
person = json.loads(json_string)
print("Name:", person["name"])
print("Languages:", person["languages"])
Name: Durai
Languages: ['Tamil', 'Malayalam']
Example 4: Reading JSON Data from a File
Use json.load()
to read JSON data from a file.
# Reading JSON data from a file
import json
with open("person.json", "r") as json_file:
person = json.load(json_file)
print("Name:", person["name"])
print("City:", person["city"])
Output Data from person.json
is read and printed.
Name: Rohini
City: Chennai
Example 5: Formatting JSON Output
Use parameters like indent
and sort_keys
to format JSON output.
# Formatting JSON output
import json
person = {
"name": "Vijay",
"age": 27,
"city": "Karur",
"languages": ["Tamil", "English"]
}
person_json = json.dumps(person, indent=4, sort_keys=True)
print("Formatted JSON:")
print(person_json)
Output JSON string formatted with indentation and sorted keys.
{ "age": 27, "city": "Karur", "languages": [ "Tamil", "English" ], "name": "Vijay" }
Example 6: Encoding Custom Objects
Serialize custom Python objects using a custom encoder.
# Encoding custom objects
import json
default_person = {
"name": "Akila",
"age": 26,
"city": "Sivaganga"
}
class Person:
def __init__(self, name, age, city):
self.name = name
self.age = age
self.city = city
person = Person("Akila", 26, "Sivaganga")
def person_encoder(obj):
if isinstance(obj, Person):
return obj.__dict__
else:
raise TypeError("Type not serializable")
person_json = json.dumps(person, default=person_encoder)
print("Custom Object JSON:", person_json)
Custom Object JSON: {"name": "Akila", "age": 26, "city": "Sivaganga"}
Example 7: Decoding JSON into Custom Objects
Deserialize JSON data into custom Python objects.
# Decoding JSON into custom objects
import json
class Person:
def __init__(self, name, age, city):
self.name = name
self.age = age
self.city = city
def person_decoder(obj):
return Person(obj['name'], obj['age'], obj['city'])
person_json = '{"name": "Dhanalakshmi", "age": 29, "city": "Madurai"}'
person = json.loads(person_json, object_hook=person_decoder)
print("Name:", person.name)
print("City:", person.city)
Name: Dhanalakshmi
City: Madurai
Example 8: Handling JSON Errors
Use try-except blocks to handle JSON decoding errors.
# Handling JSON errors
import json
invalid_json = '{"name": "John", "age": 31, "city": "Karur",}'
try:
data = json.loads(invalid_json)
except json.JSONDecodeError as e:
print("JSON decode error:", e)
JSON decode error: Expecting property name enclosed in double quotes: line 1 column 49 (char 48)
Example 9: Working with Nested JSON Data
Access nested JSON data after parsing.
# Working with nested JSON data
import json
json_string = '''{
"company": "Tech Solutions",
"employees": [
{"name": "Karthick AG", "age": 30},
{"name": "Durai", "age": 28},
{"name": "Rudra", "age": 25}
]
}'''
data = json.loads(json_string)
for employee in data["employees"]:
print("Employee Name:", employee["name"])
Employee Name: Karthick AG
Employee Name: Durai
Employee Name: Rudra
Example 10: Serializing Data with Non-ASCII Characters
Handle non-ASCII characters in JSON data.
# Handling non-ASCII characters
import json
person = {
"name": "கார்த்திக் ஏ.ஜி.", # Karthick AG in Tamil script
"city": "திருச்சி" # Trichy in Tamil script
}
person_json = json.dumps(person, ensure_ascii=False)
print("JSON with Non-ASCII Characters:")
print(person_json)
JSON with Non-ASCII Characters:
{"name": "கார்த்திக் ஏ.ஜி.", "city": "திருச்சி"}
Example 11: Comparing JSON Data
Compare two JSON objects for equality.
# Comparing JSON data
import json
json1 = '{"name": "Banumathi", "age": 50}'
json2 = '{"age": 50, "name": "Banumathi"}'
data1 = json.loads(json1)
data2 = json.loads(json2)
are_equal = data1 == data2
print("Are JSON objects equal?", are_equal)
Are JSON objects equal? True
Example 12: Merging JSON Objects
Merge two JSON objects into one.
# Merging JSON objects
import json
json1 = '{"name": "Riya", "age": 22}'
json2 = '{"city": "Trichy", "languages": ["Tamil", "Hindi"]}'
data1 = json.loads(json1)
data2 = json.loads(json2)
merged_data = {**data1, **data2}
print("Merged Data:", merged_data)
Merged Data: {'name': 'Riya', 'age': 22, 'city': 'Trichy', 'languages': ['Tamil', 'Hindi']}
Example 13: Pretty Printing JSON Data
Use the pprint
module to display JSON data in a readable format.
# Pretty printing JSON data
import json
from pprint import pprint
json_string = '{"name": "John", "age": 31, "city": "Karur", "languages": ["English", "French"]}'
data = json.loads(json_string)
pprint(data)
{'age': 31, 'city': 'Karur', 'languages': ['English', 'French'], 'name': 'John'}
Example 14: Using jsonlines
Format
Work with JSON Lines format for streaming JSON data.
# Writing data in JSON Lines format
import json
persons = [
{"name": "Karthick AG", "age": 30},
{"name": "Vijay", "age": 27},
{"name": "Rohini", "age": 25}
]
with open("persons.jl", "w") as f:
for person in persons:
json_line = json.dumps(person)
f.write(json_line + '\n')
Output A file named persons.jl
containing JSON lines.
Example 15: Validating JSON Data
Validate JSON data against a schema using the jsonschema
library.
# Validating JSON data
import json
from jsonschema import validate, ValidationError
person_schema = {
"type": "object",
"properties": {
"name": {"type": "string"},
"age": {"type": "integer"}
},
"required": ["name", "age"]
}
json_string = '{"name": "Tamilmaran", "age": "thirty"}'
data = json.loads(json_string)
try:
validate(instance=data, schema=person_schema)
print("JSON data is valid.")
except ValidationError as e:
print("JSON data is invalid:", e)
Note: You need to install jsonschema
using pip install jsonschema
.
JSON data is invalid: 'thirty' is not of type 'integer'
Explanation: The json
module in Python is powerful and easy to use for working with JSON data. By mastering its functions, you can serialize and deserialize data, handle custom objects, and interact with APIs that use JSON.