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. In Python, you can work with JSON using the json
module, which provides functions to encode (serialize) and decode (deserialize) JSON data.
Encoding (Serializing) JSON
To convert a Python object into a JSON string, you can use the json.dumps()
function. Here’s an example:
import json
data = {
"name": "John",
"age": 30,
"city": "New York",
"isStudent": False,
"courses": ["Math", "Science"]
}
json_string = json.dumps(data)
print(json_string)
Decoding (Deserializing) JSON
To convert a JSON string back into a Python object, you can use the json.loads()
function. Here’s an example:
json_string = '{"name": "John", "age": 30, "city": "New York", "isStudent": false, "courses": ["Math", "Science"]}'
data = json.loads(json_string)
print(data)