GeezerVisonThe World Wide Web, restored to 800 pixels of glory. | ||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
| Home|About|Gaming cabinet|Archives|How it works|Starter sites | ||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
GeezerVison is showing www.tutorialspoint.com — Python - JSON
Selected Reading
Python - JSONJSON in PythonJSON in Python is a popular data format used for data exchange between systems. The json module provides functions to work with JSON data, allowing you to serialize Python objects into JSON strings and deserialize JSON strings back into Python objects. 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. It is mainly used to transmit data between a server and web application as text. JSON SerializationJSON serialization is the process of converting a Python object into a JSON format. This is useful for saving data in a format that can be easily transmitted or stored, and later reconstructed back into its original form. Python provides the json module to handle JSON serialization and deserialization. We can use the json.dumps() method for serialization in this module. You can serialize the following Python object types into JSON strings −
ExampleFollowing a basic example of how to serialize a Python dictionary into a JSON string − import json
# Python dictionary
data = {"name": "Alice", "age": 30, "city": "New York"}
# Serialize to JSON string
json_string = json.dumps(data)
print(json_string)
It will produce the following output − {"name": "Alice", "age": 30, "city": "New York"}
JSON DeserializationJSON deserialization is the process of converting a JSON string back into a Python object. This is essential for reading and processing data that has been transmitted or stored in JSON format. In Python, we can use json.loads() method to deserialize JSON data from a string, and json.load() method to deserialize JSON data from a file. Example: Deserialize JSON string to Python objectIn the following example we are deserializing a JSON string into a Python dictionary using the json.loads() method − import json
# JSON string
json_string = '{"name": "John", "age": 30, "is_student": false,
"courses": ["Math", "Science"], "address": {"city": "New York", "state": "NY"}}'
# Deserialize JSON string to Python object
python_obj = json.loads(json_string)
print(python_obj)
Following is the output of the above code − {'name': 'John', 'age': 30, 'is_student': False, 'courses': ['Math', 'Science'],
'address': {'city': 'New York', 'state': 'NY'}}
Example: Deserialize JSON from FileNow, to read and deserialize JSON data from a file, we use the json.load() method − import json
# Read and deserialize from file
with open("data.json", "r") as f:
python_obj = json.load(f)
print(python_obj)
Output of the above code is as follows − {'name': 'John', 'age': 30, 'is_student': False, 'courses': ['Math', 'Science'],
'address': {'city': 'New York', 'state': 'NY'}}
Advanced JSON HandlingIf your JSON data includes objects that need special handling (e.g., custom classes), you can define custom deserialization functions. Use the object_hook parameter of json.loads() or json.load() method to specify a function that will be called with the result of every JSON object decoded. ExampleIn the example below, we are demonstrating the usage of custom object serialization − import json
from datetime import datetime
# Custom deserialization function
def custom_deserializer(dct):
if 'joined' in dct:
dct['joined'] = datetime.fromisoformat(dct['joined'])
return dct
# JSON string with datetime
json_string = '{"name": "John", "joined": "2021-05-17T10:15:00"}'
# Deserialize with custom function
python_obj = json.loads(json_string, object_hook=custom_deserializer)
print(python_obj)
We get the output as shown below − {'name': 'John', 'joined': datetime.datetime(2021, 5, 17, 10, 15)}
JSONEncoder ClassThe JSONEncoder class in Python is used to encode Python data structures into JSON format. Each Python data type is converted into its corresponding JSON type, as shown in the following table −
The JSONEncoder class is instantiated using the JSONEncoder() constructor. The following important methods are defined in this class −
ExampleIn the following example, we are encoding Python list object. We use the iterencode() method to display each part of the encoded string − import json
data = ['Rakesh', {'marks': (50, 60, 70)}]
e = json.JSONEncoder()
# Using iterencode() method
for obj in e.iterencode(data):
print(obj)
It will produce the following output − ["Rakesh", { "marks" : [50, 60, 70]}]
JSONDecoder classThe JSONDecoder class is used to decode a JSON string back into a Python data structure. The main method in this class is decode(). ExampleIn this example, the "JSONEncoder" is used to encode a Python list into a JSON string, and the "JSONDecoder" is then used to decode the JSON string back into a Python list − import json
data = ['Rakesh', {'marks': (50, 60, 70)}]
e = json.JSONEncoder()
s = e.encode(data)
d = json.JSONDecoder()
obj = d.decode(s)
print(obj, type(obj))
The result obtained is as shown below − ['Rakesh', {'marks': [50, 60, 70]}] <class 'list'>
Python JSON Module MethodsThe json module in Python provides methods for working with JSON (JavaScript Object Notation). It allows you to serialize and deserialize Python objects to and from JSON format, which is a commonly used data interchange format. Core FunctionsThe core functions in the json module allow you to serialize and deserialize JSON data.
JSON Encoder MethodsJSON encoder methods handle the conversion of Python objects to JSON format.
JSON Decoder MethodsJSON decoder methods handle the conversion of JSON data into Python objects.
Utility FunctionsUtility functions provide a simple way to process JSON data in Python.
Dunder (Magic) Methods in JSONEncoderThese are the special methods for the JSONEncoder class in the json module that enable custom behavior for JSON serialization.
Dunder (Magic) Methods in JSONDecoderThese are the special methods for the JSONDecoder class that enable custom behavior for JSON deserialization.
Functions in json.encoder (Internal Utility Functions)These functions are used internally in the json.encoder module to handle specific encoding tasks.
Functions in json.decoder (Internal Utility Functions)These functions are used internally in the json.decoder module to handle specific decoding tasks.
Attributes in json ModuleAttributes that provide various configuration settings and constants within the json module.
Attributes in json.encoderAttributes related to encoding functionality in the json.encoder module.
Attributes in json.decoderAttributes related to decoding functionality in the json.decoder module.
Attributes in JSON (For Internal Use)These attributes are for internal use in the json module.
Advertisements
| ||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
| You are visitor 01402503 — GeezerVison does not store the pages you look up. Best viewed with Netscape Navigator 4.7 or Internet Explorer 6 at 800×600. No cookies required. |