【问题标题】:import json to csv in python在python中将json导入csv
【发布时间】:2016-08-09 14:39:25
【问题描述】:

当我使用以下代码时,即使它创建了 csv 文件,我也会不断收到错误消息。我需要帮助,而且对 python 还很陌生。

我收到的错误是“回溯(最近一次通话最后一次): 文件“/home/ubuntu/workspace/parse-json.py”,第 34 行,在 values = [ x.encode('utf8') for x in item['fields'].values() ] TypeError: 字符串索引必须是整数"

import json
from pprint import pprint

with open('data.json') as data_file:    
data = json.load(data_file)

#pprint(data)

# calc number of alert records in json file
x = len(data['alerts'])


count = 0
while (count < x):
    #print 'COUNT = ', count
    print data['alerts'][count]['message']
    print data['alerts'][count]['tags']
    print data['alerts'][count]['teams']
    print data['alerts'][count]['id']
    count = count + 1

import json
import csv

f = open('data.json') 
data = json.load(f)
f.close()

f = csv.writer(open('yes.csv', 'wb+'))

for item in data:
    values = [ x.encode('utf8') for x in item['fields'].values() ]
    f.writerow([item['pk'], item['model']] + values)

【问题讨论】:

  • 这两个文件是分开的吗?您有两次相同的导入。
  • 另外,我们无法诊断您的问题,因为我们没有您的数据。创建一个MVCE,最好将data.json 的一部分直接用作字符串,而不是将其留在文件中。 (这样做甚至可能使问题对您来说显而易见。)

标签: python json csv


【解决方案1】:

您需要检查您的数据结构。 基本上错误的意思是item 不是字典。

根据我在您的代码中看到的内容,您正在迭代 data,但 data 不是字典列表,而是字典本身。

如果你想遍历字典中的元素,你应该执行以下操作之一:

for key, value in data.items():

或者如果您只想遍历值:

for value in data.values():

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2015-07-10
    • 2015-09-23
    • 2017-12-15
    • 2014-08-01
    • 2016-10-09
    • 1970-01-01
    • 2015-07-06
    相关资源
    最近更新 更多