JSON data serialization¶
JSON data serialization is the process of converting structured data into the JSON (JavaScript Object Notation) format for storage or transmission.^[400-devops-09-scripting-language-python-introduction-part-4http-readme.md]
Usage in Web Applications¶
JSON is widely adopted as a standard format for transporting data in web HTTP applications.^[400-devops-09-scripting-language-python-introduction-part-4http-readme.md] For instance, an application may request customer data from a server, which responds by sending back JSON that the receiver can easily process.^[400-devops-09-scripting-language-python-introduction-part-4http-readme.md]
Serialization and Deserialization¶
Serialization involves converting a data structure (like a Python dictionary or object) into a JSON string, while deserialization parses a JSON string back into native data structures.
In Python, the json module provides methods for these operations:
- Serializing (Writing): The
json.dumps()method converts a Python object into a JSON formatted string to be written to a file.^[400-devops-09-scripting-language-python-introduction-part-4http-readme.md] - Deserializing (Reading): The
json.loads()method parses a JSON string (read from a file) and converts it back into a Python object, such as a dictionary.^[400-devops-09-scripting-language-python-introduction-part-4http-readme.md]
Python Example¶
The following example demonstrates reading a JSON file, deserializing it into a dictionary, modifying the data, and serializing it back to a file:
import json
def updateCustomers(customers):
# Serialize dictionary to JSON string and write to file
with open('customers.json', 'w', newline='') as customerFile:
customerJSON = json.dumps(customers)
customerFile.write(customerJSON)
def getCustomers():
# Read file and deserialize JSON string to dictionary
if os.path.isfile("customers.json"):
with open('customers.json', newline='') as customerFile:
data = customerFile.read()
customers = json.loads(data)
return customers
else:
return {}
^[400-devops-09-scripting-language-python-introduction-part-4http-readme.md]
Data Representation¶
JSON typically represents data as key-value pairs. It is often used to store lists of objects, such as customer records containing IDs and names^[400-devops-09-scripting-language-python-introduction-part-4http-readme.md].
Sources¶
400-devops-09-scripting-language-python-introduction-part-4http-readme.md
Related¶
- [[Python]]
- [[HTTP]]
- [[Flask]]
- [[CSV]]