数据未正确写入JSON文件

huangapple go评论50阅读模式
英文:

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)

huangapple
  • 本文由 发表于 2023年2月24日 00:48:39
  • 转载请务必保留本文链接:https://go.coder-hub.com/75547856.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定