How to dynamically build a JSON object with Python?

后端 未结 5 1751
没有蜡笔的小新
没有蜡笔的小新 2020-11-28 18:04

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

相关标签:
5条回答
  • 2020-11-28 18:23

    You can use EasyDict library (doc):

    EasyDict allows to access dict values as attributes (works recursively). A Javascript-like properties dot notation for python dicts.

    USEAGE

    >>> from easydict import EasyDict as edict
    >>> d = edict({'foo':3, 'bar':{'x':1, 'y':2}})
    >>> d.foo
    3
    >>> d.bar.x
    1
    
    >>> d = edict(foo=3)
    >>> d.foo
    3
    

    [INSTALLATION]:

    • pip install easydict
    0 讨论(0)
  • 2020-11-28 18:23

    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)
    

    0 讨论(0)
  • 2020-11-28 18:26

    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})
    
    0 讨论(0)
  • 2020-11-28 18:37

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

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

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

    0 讨论(0)
  • 2020-11-28 18:37

    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()
    
    0 讨论(0)
提交回复
热议问题