英文:
Data not writing correctly to JSON file
问题
I'm trying to write data to JSON file, but it is not writing it correctly and I can't find out why
import json
person = {
"Name": "William",
"Age": 30,
"full-time": True
}
personJSON = json.dumps(person, indent=4, sort_keys=True)
with open('person.json', 'w') as file:
json.dump(personJSON, file)
This is what it writes to the file:
{
"Age": 30,
"Name": "William",
"full-time": true
}
I've been looking online and the code seems fine to me
英文:
I'm trying to write data to JSON file, but it is not writing it correctly and I can't find out why
import json
person = {
"Name": "William",
"Age": 30,
"full-time": True
}
personJSON = json.dumps(person, indent=4, sort_keys=True)
with open('person.json', 'w') as file:
json.dump(personJSON, file)
This is what it writes to the file "{\n \"Age\": 30,\n \"Name\": \"William\",\n \"full-time\": true\n}"
I've been looking online and the code seems fine to me
答案1
得分: 3
不要连续使用.dumps
和.dump
,只使用后者,即
import json
person = {
"Name": "William",
"Age": 30,
"full-time": True
}
with open('person.json', 'w') as file:
json.dump(person, file, indent=4, sort_keys=True)
英文:
Do not use .dumps
and .dump
subsequently, just use latter i.e. do
import json
person = {
"Name": "William",
"Age": 30,
"full-time": True
}
with open('person.json', 'w') as file:
json.dump(person, file, indent=4, sort_keys=True)
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论