简体   繁体   中英

Python - adding an element to a json file

Working with a json file in my python program. I need to modify the json file from within a function to add an empty "placeholder" element. I just want to add an empty element for a key contained in the convID object. Does the json library allow for a simpler way to append an element to a json file?

example.json:

{"1005672": "Testing needles note", "1005339": "Reply", "988608": "Received the message"}

I would like this to happen ( convID denotes the key stored in convID object):

{"1005672": "Testing needles note", "1005339": "Reply", "988608": "Received the message", "*convID*": "none"}

I'm guessing I will have to load the json into a dictionary object, make the modifications and write it back to the file... but this is proving difficult for me as I am still learning. Here's my swing at it:

def updateJSON():
   jsonCache={} # type: Dict

   with open(example.json) as j:
      jsonCache=json.load(j)

   *some code to make append element modification

    with open('example.json', 'w') as k:
       k.write(jsonCache)

Please use PEP8 style guidelines.

Following code piece would work

import json

def update_json():
    with open('example.json', 'r') as file:
        json_cache = json.load(file)
        json_cache['convID'] = None
    with open('example.json', 'w') as file:
        json.dump(json_cache, file)

To add a key to a dict, you simply name it:

your_dict['convID'] = 'convID_value'

So, your code would be something like:

import json

# read a file, or get a string
your_json = '{"1005672": "Testing needles note", "1005339": "Reply", "988608": "Received the message"}'

your_dict = json.loads(your_json)

your_dict['convID'] = 'convID_value'

So, using it with your code, it will be:

def update_json():
    json_cache = {}

    with open('example.json', 'r') as j:
        json_cache = json.load(j)

    json_cache['convID'] = 'the value you want'

    with open('example.json', 'w') as k:
        json.dump(json_cache, f)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM