Python To Generate Dynamic Nested Json String
Last Updated :
26 Feb, 2024
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. In Python, working with dynamic nested JSON strings is a common task, especially when dealing with complex data structures. In this article, we’ll explore some generally used methods to generate dynamic nested JSON strings in Python.
Python To Generate Dynamic Nested Json String
Below, are the methods of Python To Generate Dynamic Nested JSON String in Python.
Generate Dynamic Nested Json String Using Python Dictionaries
In this example, The code defines a Python dictionary `data_dict` representing nested data with attributes like name, age, address, and contacts. It then uses the `json. dumps()` function to convert the dictionary into a formatted JSON string (`json_string_dict`) with an indentation of 2 spaces.
Python3
import json
data_dict = {
"name" : "John" ,
"age" : 25 ,
"address" : { "city" : "Cityville" , "zip" : "12345" },
"contacts" : [{ "type" : "email" , "value" : "john@example.com" }]
}
json_string_dict = json.dumps(data_dict, indent = 2 )
print ( "Output" )
print (json_string_dict)
|
Output
Output
{
"name": "John",
"age": 25,
"address": {
"city": "Cityville",
"zip": "12345"
},
"contacts": [
{
"type": "email",
"value": "john@example.com"
}
]
}
Generate Dynamic Nested Json String Using Python Objects
In this example, This code defines a Python class `Person` with attributes like name, age, address, and contacts. An instance `person_obj` is created with specific values. The `serialize` function is used to customize serialization, converting the object to a dictionary. The `json.dumps()` function then converts the custom object into a JSON-formatted string (`json_string_obj`) with an indentation of 2 spaces.
Python3
import json
class Person:
def __init__( self , name, age, address, contacts):
self .name = name
self .age = age
self .address = address
self .contacts = contacts
person_obj = Person( "Jane" , 30 , { "city" : "Townsville" , "zip" : "54321" }, [{ "type" : "email" , "value" : "jane@example.com" }])
def serialize(obj):
if isinstance (obj, Person):
return obj.__dict__
return obj
json_string_obj = json.dumps(person_obj, default = serialize, indent = 2 )
print ( "\nOutput" )
print (json_string_obj)
|
Output
Output
{
"name": "Jane",
"age": 30,
"address": {
"city": "Townsville",
"zip": "54321"
},
"contacts": [
{
"type": "email",
"value": "jane@example.com"
}
]
}
Generate Dynamic Nested Json String Using Recursive Functions
In this example, This code utilizes a recursive function `convert_to_json` to handle nested structures. It recursively traverses the input data (`data_recursive`), converting dictionaries and lists into nested structures. The resulting JSON-formatted string (`json_string_recursive`) is generated with an indentation of 2 spaces .
Python3
import json
def convert_to_json(obj):
if isinstance (obj, dict ):
return {key: convert_to_json(value) for key, value in obj.items()}
elif isinstance (obj, list ):
return [convert_to_json(item) for item in obj]
else :
return obj
data_recursive = {
"name" : "Alice" ,
"age" : 28 ,
"address" : { "city" : "Villagetown" , "zip" : "67890" },
"contacts" : [{ "type" : "email" , "value" : "alice@example.com" }]
}
json_string_recursive = json.dumps(convert_to_json(data_recursive), indent = 2 )
print ( "\nMethod 3:" )
print (json_string_recursive)
|
Output
Method 3:
{
"name": "Alice",
"age": 28,
"address": {
"city": "Villagetown",
"zip": "67890"
},
"contacts": [
{
"type": "email",
"value": "alice@example.com"
}
]...
Conclusion
In conclusion, Python provides versatile methods for generating dynamic nested JSON strings, catering to different preferences and requirements. Whether utilizing dictionaries, custom objects, or recursive functions, developers can choose the approach that best fits their specific use case. The simplicity of dictionaries makes them suitable for straightforward structures, while custom objects and recursive functions offer flexibility for handling more complex nested data.
Share your thoughts in the comments
Please Login to comment...