我正在学习Python,并试图将GitHub问题转换为可读的形式。使用“如何将JSON转换为CSV?”,我想到了这个:

import json
import csv

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

f = open("issues.csv", "wb+")
csv_file = csv.writer(f)

csv_file.writerow(["gravatar_id", "position", "number", "votes", "created_at", "comments", "body", "title", "updated_at", "html_url", "user", "labels", "state"])

for item in data:
    csv_file.writerow([item["gravatar_id"], item["position"], item["number"], item["votes"], item["created_at"], item["comments"], item["body"], item["title"], item["updated_at"], item["html_url"], item["user"], item["labels"], item["state"]])

”问题。json”是包含我的GitHub问题的json文件。当我试着运行它时,我得到

File "foo.py", line 14, in <module>
csv_file.writerow([item["gravatar_id"], item["position"], item["number"], item["votes"], item["created_at"], item["comments"], item["body"], item["title"], item["updated_at"], item["html_url"], item["user"], item["labels"], item["state"]])

TypeError: string indices must be integers

我错过了什么?哪些是“字符串索引”?我敢肯定,一旦我得到这个工作,我将有更多的问题,但现在,我只是喜欢这个工作!

当我把for语句调整为简单

for item in data:
    print item

我得到的是…“问题”——所以我做错了一些更基本的事情。以下是我的JSON内容:

{"issues": [{"gravatar_id": "44230311a3dcd684b6c5f81bf2ec9f60", "position": 2.0, "number": 263, "votes": 0, "created_at": "2010/09/17 16:06:50 -0700", "comments": 11, "body": "Add missing paging (Older>>) links...

当我打印数据时,它看起来很奇怪:

{u'issues': [{u'body': u'Add missing paging (Older>>) lin...

当前回答

Item很可能是代码中的字符串;字符串索引是方括号中的索引,例如,gravatar_id。首先我要检查你的数据变量,看看你收到了什么;我猜数据是一个字符串列表(或至少包含至少一个字符串的列表),而它应该是一个字典列表。

其他回答

Item很可能是代码中的字符串;字符串索引是方括号中的索引,例如,gravatar_id。首先我要检查你的数据变量,看看你收到了什么;我猜数据是一个字符串列表(或至少包含至少一个字符串的列表),而它应该是一个字典列表。

如何读取这个JSON的第一个元素? 当文件像这样显示时

for i in data[1]:
print("Testing"+i['LocalObservationDateTime'])

这对我没用。 下面是JSON文件

[ { "LocalObservationDateTime":"2022-09-15T19:05:00+02:00", "EpochTime":1663261500, "WeatherText":"Mostly cloudy", "WeatherIcon":6, "HasPrecipitation":false, "PrecipitationType":"None", "IsDayTime":true, "Temperature":{ "Metric":{ "Value":11.4, "Unit":"C", "UnitType":17 }, "Imperial":{ "Value":52.0, "Unit":"F", "UnitType":18 } }, "RealFeelTemperature":{ "Metric":{ "Value":8.4, "Unit":"C", "UnitType":17, "Phrase":"Chilly" } } }, { "LocalObservationDateTime":"2022-09-16T19:05:00+02:00", "EpochTime":1663261500, "WeatherText":"Mostly cloudy", "WeatherIcon":6, "HasPrecipitation":false, "PrecipitationType":"None", "IsDayTime":true, "Temperature":{ "Metric":{ "Value":11.4, "Unit":"C", "UnitType":17 }, "Imperial":{ "Value":52.0, "Unit":"F", "UnitType":18 } }, "RealFeelTemperature":{ "Metric":{ "Value":8.4, "Unit":"C", "UnitType":17, "Phrase":"Chilly" } } } ]

Data是一个字典对象。因此,像这样迭代它:

Python 2

for key, value in data.iteritems():
    print key, value

Python 3

for key, value in data.items():
    print(key, value)

我有一个类似的问题与熊猫,你需要使用iterrows()函数迭代通过熊猫数据集熊猫文档iterrows

data = pd.read_csv('foo.csv')
for index,item in data.iterrows():
    print('{} {}'.format(item["gravatar_id"], item["position"]))

注意,您需要处理由函数返回的数据集中的索引。

根据经验,当我在Python中收到这个错误时,我会将函数签名与函数执行进行比较。

例如:

def print_files(file_list, parent_id):
    for file in file_list:
        print(title: %s, id: %s' % (file['title'], file['id']

因此,如果我用错误的参数顺序调用这个函数,并将列表作为第二个参数,将字符串作为第一个参数:

print_files(parent_id, list_of_files) # <----- Accidentally switching arguments location

该函数将尝试遍历parent_id字符串而不是file_list,它将期望将索引视为指向字符串中特定字符的整数,而不是字符串(title或id)的索引。

这将导致TypeError:字符串索引必须为整数错误。

由于它的动态特性(与Java、c#或Typescript等语言相反),Python不会通知你这个语法错误。