How to append in a json file in Python?

后端 未结 3 1197
无人及你
无人及你 2020-12-01 06:14

I have the a json file whose contents is {\"67790\": {\"1\": {\"kwh\": 319.4}}}. Now I create a dictionary a_dict which I need to append it into th

相关标签:
3条回答
  • 2020-12-01 06:42

    Assuming you have a test.json file with the following content:

    {"67790": {"1": {"kwh": 319.4}}}
    

    Then, the code below will load the json file, update the data inside using dict.update() and dump into the test.json file:

    import json
    
    a_dict = {'new_key': 'new_value'}
    
    with open('test.json') as f:
        data = json.load(f)
    
    data.update(a_dict)
    
    with open('test.json', 'w') as f:
        json.dump(data, f)
    

    Then, in test.json, you'll have:

    {"new_key": "new_value", "67790": {"1": {"kwh": 319.4}}}
    

    Hope this is what you wanted.

    0 讨论(0)
  • 2020-12-01 06:45

    You need to update the output of json.load with a_dict and then dump the result. And you cannot append to the file but you need to overwrite it.

    0 讨论(0)
  • 2020-12-01 06:47
    json_obj=json.dumps(a_dict, ensure_ascii=False)
    
    0 讨论(0)
提交回复
热议问题