python - JSON 格式不对

标签 python json

我有一个高分,作为这样的结构:

[(300, 'Test'), (400, 'Test1'), (500, 'Test2'), (500, 'Test2'), (600, 'Test2'), (5, 'Test2'), (500, 'Test2'), (600, 'Test2'), (300, 'Test2'), (100, 'Test2')]
我需要像这样获取 JSON 格式:
{"Test":300, "Test1":400.....}
但是我怎么努力我只能得到这样的结果:
[["Test":300],["Test1":400],....]
我怎样才能得到正确的 json 格式?我正在使用 json.dumps(highscore) 也试过 son.dumps({highscore})

最佳答案

先将元组列表转换为字典,然后再将其传递给 json.dumps() .

import json

a = [(300, 'Test'), (400, 'Test1'), (500, 'Test2'), (500, 'Test2'), (600, 'Test2'), (5, 'Test2'), (500, 'Test2'), (600, 'Test2'), (300, 'Test2'), (100, 'Test2')]

rs = json.dumps(dict(a))

print(rs)
>>>{"300": "Test2", "400": "Test1", "500": "Test2", "600": "Test2", "5": "Test2", "100": "Test2"}
编辑 :
如果你想交换 json 对象中的键和值,你可以先交换元组位置,但是你只能保留每个键值对的单个实例,因为字典只能保留唯一键。
a = [(300, 'Test'), (400, 'Test1'), (500, 'Test2'), (500, 'Test2'), (600, 'Test2'), (5, 'Test2'), (500, 'Test2'), (600, 'Test2'), (300, 'Test2'), (100, 'Test2')]

swap = [(y,x) for x,y in a]

res = json.dumps(dict(swap))

print(res)
>>>{"Test": 300, "Test1": 400, "Test2": 100}

关于python - JSON 格式不对,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/68147915/

相关文章:

arrays - jq - 将对象列表转换为汇总对象

python - 在 pisa html 到 pdf 库中使用图像 URL 进行 link_callback

python - 在 Python 中格式化数字以在 plt.colorbar() 上使用逗号

使用单词列表的 Python 字符串比较

android Volley删除方法,为什么会发送空参数

c# - 如何在 "azure function"上模拟 HttpRequest

java - 如何在 DTO 中隐藏 JsonProperty?

python - 如何在python中将某些范围的列展平成一个?

python - 如何开始使用谷歌应用引擎?

json - 快速搜索 JSON