{"code":"200","result":{"302057481046073372":{"302057481046073372":1.0523923348283815,"304479743393312815":0.9959330071167308,"304024895354912851":1.026913867116934,"307989838517305346":1.001794250183725,"304523006938624018":1.022248796233928,"311147024898777163":1.0455741541960053,"304583930458320940":1.0043062129393774,"304478935071223852":0.9977272639845888,"310005069955301460":0.9797846817416752,"304035445505945643":1.026913867116934,"305025908043956252":0.9965310932087248,"302324522575515690":1.026913867116934,"302390854109220868":0.9821770261096512,"305721814351507540":0.9911483187372659,"304019923427037230":1.026913867116934,"349358108339961878":0.9971291793007189,"305753420650786875":0.9910287008664957,"304007366385389620":1.026913867116934,"304069952887947328":1.0208133886827109,"308129789586223120":1.028947360760145}},"message":"成功"}请根据以上json文件的数据格式,用python处理以上json串 处理方式:把,换成_ 把换行去掉。 输出格式:csv格式,表头3列,分别为id,related id, xiangsizhi,且根据xiangsizhi进行倒序排列
时间: 2023-07-21 12:58:35 浏览: 252
se.rar_it_site:www.pudn.com
您可以使用以下代码来处理给定的 JSON 数据,并将其转换为 CSV 格式的输出:
```python
import json
import csv
# JSON 数据
json_data = '''
{"code":"200","result":{"302057481046073372":{"302057481046073372":1.0523923348283815,"304479743393312815":0.9959330071167308,"304024895354912851":1.026913867116934,"307989838517305346":1.001794250183725,"304523006938624018":1.022248796233928,"311147024898777163":1.0455741541960053,"304583930458320940":1.0043062129393774,"304478935071223852":0.9977272639845888,"310005069955301460":0.9797846817416752,"304035445505945643":1.026913867116934,"305025908043956252":0.9965310932087248,"302324522575515690":1.026913867116934,"302390854109220868":0.9821770261096512,"305721814351507540":0.9911483187372659,"304019923427037230":1.026913867116934,"349358108339961878":0.9971291793007189,"305753420650786875":0.9910287008664957,"304007366385389620":1.026913867116934,"304069952887947328":1.0208133886827109,"308129789586223120":1.028947360760145}},"message":"成功"}
'''
# 解析 JSON 数据
data = json.loads(json_data)
# 转换为 CSV 格式
csv_data = []
for key, values in data["result"].items():
for related_id, xiangsizhi in values.items():
csv_data.append([key, related_id, xiangsizhi])
# 根据 xiangsizhi 进行倒序排序
csv_data.sort(key=lambda x: x[2], reverse=True)
# 写入 CSV 文件
with open("output.csv", "w", newline="") as csv_file:
writer = csv.writer(csv_file)
writer.writerow(["id", "related id", "xiangsizhi"]) # 写入表头
writer.writerows(csv_data)
print("CSV 文件已生成!")
```
这段代码首先将给定的 JSON 数据解析为 Python 字典对象。然后,它遍历字典并将相关的数据提取到一个 CSV 数据列表中。最后,它根据 "xiangsizhi" 列进行倒序排序,并将数据写入一个名为 "output.csv" 的 CSV 文件中。
请确保在运行代码之前,将 JSON 数据替换为实际的数据。运行代码后,将生成一个名为 "output.csv" 的 CSV 文件,其中包含三列:id、related id 和 xiangsizhi,并按照 xiangsizhi 进行倒序排序。
阅读全文