JSON (JavaScript Object Notation) is a standard text format for storing and transporting data. It is highly common when data is sent from a server to a web page or between APIs.
Python has a built-in package called json, which can be used to work with JSON data.
1. JSON format
JSON looks exactly like a Python dictionary as a string.
{
"name": "John",
"age": 30,
"city": "New York"
}
2. json.loads() (JSON to Python)
If you have a JSON string, you can parse it by using the json.loads() method. The result will be a Python dictionary.
import json
# some JSON string:
x = '{"name":"John", "age":30, "city":"New York"}'
# parse x:
y = json.loads(x)
# the result is a Python dictionary:
print(y["age"]) # 30
3. json.dumps() (Python to JSON)
If you have a Python object, you can convert it into a JSON string by using the json.dumps() method.
import json
# a Python object (dict):
x = {
"name": "John",
"age": 30,
"city": "New York"
}
# convert into JSON:
y = json.dumps(x)
# the result is a JSON string:
print(y)
Formatting the Output
The json.dumps() method has parameters to make it easier to read the result.
indent: defines the numbers of indentsseparators: changes the default separatorsort_keys: specifies if the result should be sorted or not
print(json.dumps(x, indent=4, sort_keys=True))
4. Parse JSON from file (load(), dump())
If you are working with files instead of strings, you use load() and dump() (without the ‘s’).
json.load() (File to Python)
Reads a JSON file and parses it into a Python object.
import json
with open("data.json", "r") as file:
data = json.load(file)
print(data)
json.dump() (Python to File)
Writes a Python object to a file in JSON format.
import json
data = {"name": "Alice", "role": "Admin"}
with open("output.json", "w") as file:
json.dump(data, file, indent=4)
5. Convert custom objects to JSON
The json module only understands standard primitive types (dicts, lists, strings, ints, floats, booleans, None).
If you try to serialize a custom class object, it will throw a TypeError.
To convert custom objects, you must write a custom encoder, or define a method inside your class that returns a serializable dictionary format.
import json
class User:
def __init__(self, name, age):
self.name = name
self.age = age
user = User("Bob", 25)
# Convert the object's __dict__ attribute which is a dictionary of its properties
json_string = json.dumps(user.__dict__)
print(json_string) # {"name": "Bob", "age": 25}
Discussion
Loading comments...