可以通过以下步骤实现:
以下是一个示例的Python代码,用于将嵌套的Json字符串转换为csv:
import csv
import json
def json_to_csv(json_str, csv_file):
data = json.loads(json_str)
# 获取所有键
keys = set()
get_keys(data, keys)
with open(csv_file, 'w', newline='') as file:
writer = csv.DictWriter(file, fieldnames=keys)
writer.writeheader()
write_data(data, writer)
def get_keys(data, keys):
if isinstance(data, dict):
for key in data.keys():
keys.add(key)
get_keys(data[key], keys)
elif isinstance(data, list):
for item in data:
get_keys(item, keys)
def write_data(data, writer):
if isinstance(data, dict):
row = {}
for key in writer.fieldnames:
if key in data:
row[key] = data[key]
else:
row[key] = ""
writer.writerow(row)
elif isinstance(data, list):
for item in data:
write_data(item, writer)
# 示例用法
json_str = '{"name": "John", "age": 30, "address": {"city": "New York", "country": "USA"}}'
csv_file = 'output.csv'
json_to_csv(json_str, csv_file)
这段代码将会将嵌套的Json字符串转换为csv文件,并将Json数据的键作为csv文件的表头,对应的值写入csv文件的相应位置。你可以根据实际需求进行修改和扩展。
领取专属 10元无门槛券
手把手带您无忧上云