I am new to Python and I am playing with JSON data. I would like to dynamically build a JSON object by adding some key-value to an existing JSON object.
I tried the following but I get TypeError: 'str' object does not support item assignment:
There is already a solution provided which allows building a dictionary, (or nested dictionary for more complex data), but if you wish to build an object, then perhaps try ‘ObjDict’. This gives much more control over the json to be created, for example retaining order, and allows building as an object which may be a preferred representation of your concept.
pip install objdict first.
from objdict import ObjDict
data = ObjDict()
data.key = 'value'
json_data = data.dumps()
import json
print('serialization')
myDictObj ={"name":"John","age":30,"car":None}##convert object to json
serialized= json.dumps(myDictObj, sort_keys=True, indent=3)print(serialized)## now we are gonna convert json to object
deserialization=json.loads(serialized)print(deserialization)
All previous answers are correct, here is one more and easy way to do it. For example, create a Dict data structure to serialize and deserialize an object
(Notice None is Null in python and I’m intentionally using this to demonstrate how you can store null and convert it to json null)
import json
print('serialization')
myDictObj = { "name":"John", "age":30, "car":None }
##convert object to json
serialized= json.dumps(myDictObj, sort_keys=True, indent=3)
print(serialized)
## now we are gonna convert json to object
deserialization=json.loads(serialized)
print(deserialization)