Python cannot load JSON generated by json.dump

This seems like a very simple problem when I am trying to read a JSON file and modify multiple fields.

with open("example.json", "r+") as f:
    data = json.load(f)
    # perform modifications to data
    f.truncate(0)
    json.dump(data, f)

      

It worked the first time I manually created a JSON file and saved the correct JSON file, but the second time when I run the same script it gives me this error:

ValueError: JSON object could not be decoded

Why? It amazes me that the module json

cannot parse the file created by the module itself.

+3


source to share


2 answers


Based on the code you provided and what you are trying to do (return the file cursor to the beginning of the file), you are not actually doing this with f.truncate

. You are effectively truncating your file. those. clear the file completely.

In help

by method truncate

:

truncate(...)
    truncate([size]) -> None.  Truncate the file to at most size bytes.

    Size defaults to the current file position, as returned by tell().

      

What you actually want to do by moving the cursor back to the beginning of the file is using seek

.

Search help:

seek(...)
    seek(offset[, whence]) -> None.  Move to new file position.

      

So, explicitly, to go back to the beginning of the file you want f.seek(0)

.

For the sake of providing an example of what's going on. Here's what happens with truncation:



There are things in the file:

>>> with open('v.txt') as f:
...  res = f.read()
...
>>> print(res)
1
2
3
4

      

Call truncate

and see that the file will be empty:

>>> with open('v.txt', 'r+') as f:
...  f.truncate(0)
...
0
>>> with open('v.txt', 'r') as f:
...  res = f.read()
...
>>> print(res)

>>>

      

Usage f.seek(0)

:

>>> with open('v.txt') as f:
...  print(f.read())
...  print(f.read())
...  f.seek(0)
...  print(f.read())
...
1
2
3
4



0
1
2
3
4


>>>

      

The long gap between the first exit shows the cursor at the end of the file. Then we call f.seek(0)

(output 0

from call f.seek(0)

) and output our f.read()

.

+3


source


You are missing one line, f.seek(0)



with open("example.json", "r+") as f:
    data = json.load(f)
    # perform modifications to data
    f.seek(0);
    f.truncate(0)
    json.dump(data, f)

      

+1


source







All Articles