Add element to a JSON file?

后端 未结 3 1944
北恋
北恋 2020-12-14 05:44

I am trying to add an element to a json file in python but I am not able to do it.

This is what I tried untill now (with some variation which I deleted):

<         


        
相关标签:
3条回答
  • 2020-12-14 06:10

    One possible issue I see is you set your JSON unconventionally within an array/list object. I would recommend using JSON in its most accepted form, i.e.:

    test_json = { "a": 1, "b": 2}
    

    Once you do this, adding a json element only involves the following line:

    test_json["c"] = 3
    

    This will result in:

    {'a': 1, 'b': 2, 'c': 3}
    

    Afterwards, you can add that json back into an array or a list of that is desired.

    0 讨论(0)
  • alternatively you can do

    iter(data).next()['f'] = var
    
    0 讨论(0)
  • 2020-12-14 06:20

    You can do this.

    data[0]['f'] = var
    
    0 讨论(0)
提交回复
热议问题