user12083883
user12083883

Reputation:

Writing JSON object to file and getting null written instead

I'm using Python to create a data.json file and write a json object to it.

with open('data.json', 'w', encoding='utf-8') as f:
        util.json.dump(jsonData, f, ensure_ascii=False, indent=4)

where jsonData = {'Book': {'author': 'John Black', 'description': 'When....

When I locate data.json file on my computer and open it to modify the content, instead of {'Book': {'author':... I see null printed in the file. I don't understand why it is happening, jsonData is not null, I printed it out before manipulating to double-check. Thank you for your help in advance! =)

Upvotes: 1

Views: 675

Answers (2)

Avinash Dalvi
Avinash Dalvi

Reputation: 9301

import json
jsonData = {
    "Book": {
        "author": "ohn Black",
        "description": "afasffsaf afafasfsa"
    }
}

with open('data.json', 'w', encoding='utf-8') as f:
   f.write(json.dumps(jsonData))

Upvotes: 0

Saharsh
Saharsh

Reputation: 1098

I am not sure what purpose util is fulfilling here but using json library seems to be giving right results.

import json

jsonData = {'Book': {'author': 'John Black', 'description': 'When....'}}

with open('data.json', 'w', encoding='utf-8') as f:
    json.dump(jsonData, f, ensure_ascii=False, indent=4)

Upvotes: 1

Related Questions