我试图将.json文件转换为.csv,以便我可以在R中执行分析。我按照others建议的步骤操作,但仍遇到问题(可能由于json文件的大尺寸)。首先,我从网上拉URL:将大型JSON转换为CSV - Python
import urllib
#first open html as .json
response = urllib.request.urlopen("http://trends.vera.org/data/county/1003/")
input = response.read()
print(input)
这个函数下面我从链接问题得到平坦的json文件。
#function to flatten .json file
def flattenjson(b, delim):
val = {}
for i in b.keys():
if isinstance(b[i], dict):
get = flattenjson(b[i], delim)
for j in get.keys():
val[ i + delim + j ] = get[j]
else:
val[i] = b[i]
return val
下面的代码列出了一个列表并为csv生成列名。 这是哪里出问题了。有谁知道如何解决这个问题?
#find column names
input = map(lambda x: flattenjson(x), input)
columns = map(lambda x: x.keys(), input)
columns = reduce(lambda x,y: x+y, columns)
columns = list(set(columns))
print(columns)
最后,我将json数据写入.csv文件。
#write to .csv file
with open(fname, 'wb') as out_file:
csv_w = csv.writer(out_file)
csv_w.writerow(columns)
for i_r in input:
csv_w.writerow(map(lambda x: i_r.get(x, ""), columns))
在此先感谢您的帮助。
如果您收到错误,请将其发布在您的问题中。 – sisanared