1

My dictionary in a JSON file looks like this:

{
'key1':value1
'key2':value2
}

I'm writing a loop where each iteration adds a new key to the dictionary in the file. For example, after one iteration the dictionary in the file looks like this:

{
'key1':value1
'key2':value2
'key3':value3
}

I want to use a method to directly append a new key into the dictionary in the file. I don't want to have to read the file in, change data and write it back out again. Is there any way to do this?

2
  • 3
    is there a reason why you want to avoid rewriting the file? Commented Nov 8, 2014 at 23:18
  • If this is a small json file and the operation will be infrequent, just rewrite the file. If the file will be huge and/or frequent read-writes, use something else e.g. a database. Commented Nov 9, 2014 at 0:32

2 Answers 2

1

This is a rather crude implementation that assumes that the file ends with } and a newline (which explains the -2):

with open('data.json','rb+') as f:
    f.seek(-2,2)
    f.write(b"'new_key':new_value\n}\n")
Sign up to request clarification or add additional context in comments.

Comments

0

You could do this by finding the final closing curly brace and then using file.seek to go to that position. Then you can write your new values, like this:

with open(path, 'rb+') as f:
    s = f.read()
    index = s.rfind('}')
    f.seek(index)
    f.write(',\n[YOUR JSON HERE]\n')
    f.write(s[index:])

Note that if your structure is actually a list first, this will need you to use ] instead, but otherwise this should work the same. Also note that depending on whether or not you normally use trailing commas (ie. {a: 1, b: 13, c: 231,}) you might want to ommit the comma I added in the first write command.

Comments

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.