import pathlib
a=pathlib.Path(__file__).parent.absolute()
dirc=str(a)+'\\file.json'
dirc2=str(a)+'\\PrettyJson.json'
data={1: {"titolo": "yea boi", "voto": 10, "genere": "a me ne so"}, 2: {"titolo": "yea boi 2", "voto": 8, "genere": "bo"}}
def jsonPrettyPrint():
with open(dirc,'w') as json_file:
json.dump(data, json_file)
with open(dirc) as json_file:
with open(dirc2,'w') as PrettyJsonFile:
Obj = json.load(json_file)
PrettyJson = json.dumps(Obj, indent=4)
json.dump(PrettyJson,PrettyJsonFile)
print(PrettyJson)
jsonPrettyPrint()
代码在这里,可以正常工作,但是当我打印Pretty Json时,它给出了输出
{
"1": {
"titolo": "yea boi",
"voto": 10,
"genere": "a me ne so"
},
"2": {
"titolo": "yea boi 2",
"voto": 8,
"genere": "bo"
}
}
如您所见,2和1是字符串而不是整数,但是8和10是整数,idk为什么,我们将提供任何帮助
答案 0 :(得分:1)
在加载JSON之后将密钥转换为int。
with open(dirc) as json_file:
data = json.load(json_file)
for key, value in list(data.items()):
data[int(key)] = value
del data[key]
print(data)