Python orjson.loads() Method
Below are some of the examples of uses of orjson.loads() function in Python:
Basic Example of orjson.loads() Method
In this example, the JSON string is parsed using orjson.loads() and converted into a Python dictionary.
import orjson
json_string = '{"name": "John", "age": 30, "city": "New York"}'
# Parsing JSON string using orjson.loads()
data = orjson.loads(json_string)
# Displaying the parsed data
print(data)
Output:
{'name': 'John', 'age': 30, 'city': 'New York'}
Handling Nested JSON Using orjson.loads() Method
In this example, we demonstrate how orjson.loads() handles nested JSON structures, allowing us to access the data using dictionary-like syntax.
import orjson
# Nested JSON string
json_string = '{"person": {"name": "Alice", "age": 25, "city": "London"}}'
# Parsing nested JSON string
data = orjson.loads(json_string)
# Accessing nested data
print("Name:", data['person']['name'])
print("Age:", data['person']['age'])
print("City:", data['person']['city'])
Output:
Name: Alice
Age: 25
City: London
Error Handling Using orjson.loads() Method
In this example, we deliberately provide an invalid JSON string to demonstrate how orjson.loads() raises a JSONDecodeError when encountering invalid JSON syntax.
import orjson
# Invalid JSON string
json_string = '{"name": "John", "age": 30, "city": "New York"'
try:
# Parsing invalid JSON string
data = orjson.loads(json_string)
print(data)
except orjson.JSONDecodeError as e:
print("Error parsing JSON:", e)
Output:
Error parsing JSON: unexpected end of data: line 1 column 47 (char 46)
Python orjson.loads() Method
Python orjson.loads() method is used to deserialize a JSON string into a Python object using the orjson library of Python. In this article, we will learn about the Python orjson.loads() function.