0

Relatively new to JSON and Python here. Trying to make a function that adds a new entry to a JSON-file. The JSON-file (avutstyr.json) looks like this:

    {
    "Utstyr": 
    [
      {
        "id": "SKMU0001",
        "name": "Panasonic XY1234",
        "type": "Projektor 4:3"
      },
      {
        "id": "SKMU0002",
        "name": "PA uten miksebord",
        "type": "PA-system"
      }
   ]
   }

And the Python-script:

newequip = """{
"id": "SKMU0003",
"name": "Panasonic CT1212",
"type": "Projektor 16:10"
}"""

is_json(newequip)
newequip = json.loads(newequip)

print(newequip)

with open('avutstyr.json', 'a+') as f:
    data = json.load(f)
    data = data['Utstyr'].update(newequip)
    
    json.dump(data, f)

for i in data['Utstyr']:
    print(i['name'])

Getting the following error: JSONDecodeError: Expecting value

The values are there or what?

  • what is the contents of the file `avutstyr.json`? – Macattack Nov 13 '20 at 20:01
  • Consider formatting your JSON text with `jq` or similar tools to make it easier for humans to read (ad thus find problems in). – Charles Duffy Nov 13 '20 at 20:08
  • That said, using `a+` when you want to _update_ a file is... unusual. Appending a new document to the end of an old file doesn't update that file; in the case of JSON, it just makes it corrupt (since you can only have one document per file for proper JSON; it's only variants like JSONL that allow anything else). – Charles Duffy Nov 13 '20 at 20:08
  • @Macattack: Content of avutstyr.json is the JSON listed on the top part of my post. – Kenminator Nov 13 '20 at 22:00
  • @CharlesDuffy: using w erases the .json-file content and gives error: UnsupportedOperation: not readable – Kenminator Nov 13 '20 at 22:00
  • @Kenminator, did you see me telling you to change your code to use `w` (and not change anything else at the same time)? I was explaining what went wrong, not telling you how to fix it. – Charles Duffy Nov 13 '20 at 22:03
  • The best-practice way to update a file on UNIX -- the way `sed -i` does it under the hood, for example -- is to create a new, separate temporary file; write output to it; and when it's completely written, rename it over your original file. Note Python's `tempfile.NamedTemporaryFile`, which will do the work of generating a temporary file with a random name for you. – Charles Duffy Nov 13 '20 at 22:04
  • @CharlesDuffy, not at all, but it makes more sense to me with w when i think about it. – Kenminator Nov 13 '20 at 22:05
  • @CharlesDuffy, thanks. I'll try that. – Kenminator Nov 13 '20 at 22:06
  • See [atomic writing to file with python](https://stackoverflow.com/questions/2333872/atomic-writing-to-file-with-python) for some relevant discussion. (Note that the temporary file needs to be in the same directory as your output filename for the replace operation to be guaranteed to be atomic). – Charles Duffy Nov 13 '20 at 22:06

0 Answers0