【发布时间】:2021-12-28 22:43:01
【问题描述】:
我有一个从 json 获得的嵌套 json 文件。 我正在尝试通过python代码将其转换为csv。
我尝试了所有可能的方法将其转换为 csv,但未能成功。
我也遵循了以前的问题和解决方案,但对我没有用。
我的json格式是
{
"d1" : ("value1"),
"d2" : (value2-int),
"d3" : [
{
"sub-d1" : sub-value1(int),
"sub-d2" : sub-value2(int),
"sub-d3" : sub-value3(int),
"sub-d4" : [
{
"sub-sub-d1" : "sub-sub-value3",
"sub-sub-d2" : sub-value3(int)
},
{
"sub-sub-d1" : sub-sub-value3(int),
"sub-sub-d2" : "sub-sub-value3"}
]
],
"sub-d5" : "sub-value4",
"sub-d6" : "sub-value5"
}
],
"d4" : "value3",
"d5" : "value4",
"d6" : "value5,
"d7" : "value6"
}
{ another entry with same pattern..and so on}
一些值和子值有整数和str + int。
我尝试了什么
import json
import csv
import requests
with open('./data/inverter.json', 'r') as myfile:
json_data = myfile.read()
def get_leaves(item, key=None):
if isinstance(item, dict):
leaves = {}
for i in item.keys():
leaves.update(get_leaves(item[i], i))
return leaves
elif isinstance(item, list):
leaves = {}
for i in item:
leaves.update(get_leaves(i, key))
return leaves
else:
return {key : item}
# First parse all entries to get the complete fieldname list
fieldnames = set()
for entry in json_data:
fieldnames.update(get_leaves(entry).keys())
with open('output.csv', 'w', newline='') as f_output:
csv_output = csv.DictWriter(f_output, fieldnames=sorted(fieldnames))
csv_output.writeheader()
csv_output.writerows(get_leaves(entry) for entry in json_data)
这将我所有的数据保存在带有拆分值的单列中。
我尝试使用: https://github.com/vinay20045/json-to-csv.git
但这也没有用。
我还尝试使用以下代码解析和做简单的技巧:
with open("./data/inverter.json") as data_file:
data = data_file.read()
#print(data)
data_content = json.loads(data)
print(data_content)
但它会引发错误:'JSONDecodeError: Expecting value: line 2 column 13 (char 15)'
谁能帮我将嵌套的 json 转换为 csv 吗?
不胜感激。
谢谢
【问题讨论】:
-
您这里的数据看起来不像实际的 JSON - 例如,JSON 语法没有括号,并且像 sub-sub-value3 这样的项目没有用引号括起来(假设它们是有意的成为字符串)。这些数据是从哪里来的?
-
对不起,有些是整数,我忘了说。
-
重点仍然存在:括号 () 不是有效的 JSON,并且会导致您收到的消息。我问数据来自哪里的原因是它可能是 JSON 的一些特殊定制版本,可以在给定正确的库的情况下以标准方式解析。
-
我明白你的意思,我怎样才能避免这个 () 括号?我检查了这个巨大的 json 文件,我在括号()中看到了很多值 ..e.g.. NumberInt(10021).....
-
数据从何而来?如果它来自 MongoDB,您可以选择以不同的方式导出它吗?
标签: python json python-3.x mongodb python-2.7