How to dynamically build a JSON object? How to dynamically build a JSON object? python python

How to dynamically build a JSON object?


You build the object before encoding it to a JSON string:

import jsondata = {}data['key'] = 'value'json_data = json.dumps(data)

JSON is a serialization format, textual data representing a structure. It is not, itself, that structure.


You can create the Python dictionary and serialize it to JSON in one line and it's not even ugly.

my_json_string = json.dumps({'key1': val1, 'key2': val2})


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 ObjDictdata = ObjDict()data.key = 'value'json_data = data.dumps()