1

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)

2 Answers 2

2

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)
Sign up to request clarification or add additional context in comments.

2 Comments

json.load(file) and json.dump(json_cache, file) would be smarter :)
@SvenEberth Updated my answer :)
1

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)

2 Comments

Please use PEP8 guidelines for code snippet in Python.
last line needs a k instead of an f, but that worked... thank you!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.