使用python将JSON转换为CSV

时间:2014-05-29 12:49:18

标签: python json csv

我有JSON数据:

u'{"result":[{"timestamp":1356843600000,"values":{"stream:sentimentNeutral":0}},{"timestamp":1356930000000,"values":{"stream:sentimentNeutral":15672}},{"timestamp":1357016400000,"values":{"stream:sentimentNeutral":13646}},{"timestamp":1357102800000,"values":{"stream:sentimentNeutral":14301}

现在需要将其写入新的csv文件。 我得到了'响应'作为JSON

response = requests.get(end_point,params=query_params);

# pprint.pprint(response.text)


data = json.loads(response.text)


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

for item in data['result']:
 f.writerow(item['timestamp']['stream:sentimentNeutral'].values())

我收到此错误

Traceback (most recent call last):
  File "G:\Python\codevOne.py", line 26, in <module>
    f.writerow(item['timestamp']['stream:sentimentNeutral'].values())
TypeError: 'long' object has no attribute '__getitem__'
>>> 

请纠正我的错误。我觉得我正在努力穿越一个字典中的字典。 我期望的结果是名为'test.csv'的文件,其中包含时间戳行和相应的流:sentimentNeutral

2 个答案:

答案 0 :(得分:0)

编辑:添加完整测试的来源 这可以完成工作(如果我正确理解你想要的东西):

for item in data['result']:
  f.writerow((item['timestamp'], item['values']['stream:sentimentNeutral']))

它提供了由行timestamp, stream:sentimentNeutral

组成的csv文件

以下是您的数据的完整测试:

import pprint
import csv
import json

resp = u'{"result":[{"timestamp":1356843600000,"values":{"stream:sentimentNeutral":0}},{"timestamp":1356930000000,"values":{"stream:sentimentNeutral":15672}},{"timestamp":1357016400000,"values":{"stream:sentimentNeutral":13646}},{"timestamp":1357102800000,"values":{"stream:sentimentNeutral":14301}}]}'
data = json.loads(resp)
pprint.pprint(data)
with open('test_1.csv','wb+') as fd:
    f = csv.writer(fd)
    for item in data['result']:
        f.writerow((item['timestamp'], item['values']['stream:sentimentNeutral']))

pprint的输出是:

{u'result': [{u'timestamp': 1356843600000L,
              u'values': {u'stream:sentimentNeutral': 0}},
             {u'timestamp': 1356930000000L,
              u'values': {u'stream:sentimentNeutral': 15672}},
             {u'timestamp': 1357016400000L,
              u'values': {u'stream:sentimentNeutral': 13646}},
             {u'timestamp': 1357102800000L,
              u'values': {u'stream:sentimentNeutral': 14301}}]}

以下是test_1.csv

的内容
1356843600000,0
1356930000000,15672
1357016400000,13646
1357102800000,14301

答案 1 :(得分:0)

因为在您的代码中item['timestamp']是一个数值,例如,在第一个循环中,它的值是1356843600000而不是dict。

您应该使用:

for item in data['result']:
    timestamp = item['timestamp']
    value = item['values']['stream:sentimentNeutral']
    f.writerow([timestamp, value])