【问题标题】:Having a set of json and that needs to be converted to csv有一组 json 并且需要转换为 csv
【发布时间】:2019-03-05 09:50:19
【问题描述】:

{"i": "56", "m1": "IT", "m2": "Area", "r": "faced this problem"}

{"i": "57", "m1": "IT", "m2": "Area", "r": "faced this problem3"}

这是JSON的格式吗?

【问题讨论】:

  • 显示您尝试过的内容,以便轻松解决您的问题,您应该尝试 1.read json 并在 json 上循环并使用 csv.write() 将数据保存到 csv 文件
  • 通过这个MCVE .TO CHECK JSON VALIDATOR 通过这个Json validator
  • 请阅读这里的答案:How can I convert JSON to CSV?自己编写一些代码,如果您的代码不起作用,请在您的问题中发布代码。

标签: python json csv


【解决方案1】:

代码

import json

with open('input.json', "r") as in_file:
    data = json.load(in_file)

with open('output.csv', 'w') as out_file:
    for entry in data:
        out_file.write(','.join(entry.values()) + '\n')

输入.json

[
  {
    "i": "56",
    "m1": "IT",
    "m2": "Area",
    "r": "faced this problem"
  },
  {
    "i": "57",
    "m1": "IT",
    "m2": "Area",
    "r": "faced this problem3"
  }
]

输出.csv

56,IT,Area,faced this problem
57,IT,Area,faced this problem3

【讨论】:

  • 这些数据在 json 文件中,同样有很多数据。我的代码只写了一行并给出了编码错误。
  • 请解释一下。尽可能详细。
  • 有一个json文件格式的文件{"i": "56", "m1": "IT", "m2": "Area", "r": "遇到了这个问题"} ,这是一行。同样明智的是,该文件中有许多行。此数据需要传输到 csv 文件。使用 python 3.x
  • 你知道如何将 JSON 文件作为 python dict 加载到内存中吗?如果您不知道 - 在网络上快速搜索应该会有所帮助。完成 JSON 加载部分后,您将拥有“数据”(请参阅​​我的代码),您可以继续。
  • import json with open('inputfilePath', "r") as data_file: for line in data_file.readlines(): data = json.loads(line) print(data) data_file.close() with open('outputfile', 'w') as f: 用于输入数据: f.write(','.join(entry.values()) + '\n')
猜你喜欢
  • 2020-07-20
  • 2019-02-03
  • 1970-01-01
  • 2015-09-16
  • 1970-01-01
  • 2012-10-25
  • 2020-11-20
  • 2022-01-17
  • 2019-05-18
相关资源
最近更新 更多