0

i want to update a list of array in json using python i have used this

import json

with open('test.json', 'w') as file:
    d = {
        "name": 'David',
        "gender": 'Female'
    }
    data = json.load(file)
    data.append(d)
    json.dump(data, file)

and json file is test.json

[
  {
    "name": "John",
    "gender": "Male"
  },
  {
    "name": "Mary",
    "gender": "Female"
  }
]

when i run the code it shows

Traceback (most recent call last):
  File "test.py", line 8, in <module>
    data = json.load(file)
  File "C:\Users\John\anaconda3\lib\json\__init__.py", line 293, in load
    return loads(fp.read(),
io.UnsupportedOperation: not readable

i want something like this and i have also tried by changing w to r and r+

[
  {
    "name": "John",
    "gender": "Male"
  },
  {
    "name": "Mary",
    "gender": "Female"
  },
  {
    "name": "David",
    "gender": "Female"
  }
]
0

1 Answer 1

1

You've opened the file with w mode, which is only for writing the file. You can't read it. Also, that mode will truncate the file, losing the old data.

Use r+ mode to open it for reading and writing. Then you need to seek back to the beginning of the file after reading to overwrite it. And you should call truncate() in case the new contents are shorter than the old contents (that probably won't happen here because you're appending, but it could if the file originally had extra whitespace, and it's better to be safe than sorry).

with open('test.json', 'r+') as file:
    d = {
        "name": 'David',
        "gender": 'Female'
    }
    try:
        data = json.load(file)
    except json.decoder.JSONDecodeError:
        # Default to empty list if file is empty
        data = []
    data.append(d)
    file.seek(0)
    json.dump(data, file)
    file.truncate()
Sign up to request clarification or add additional context in comments.

3 Comments

json.decoder.JSONDecodeError: Expecting value: line 1 column 1 (char 0)
that's because the file is empty. You emptied it when you opened it for writing earlier.
I updated the answer to show how to handle the error

Your Answer

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