我正在学习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...

当前回答

如何读取这个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)

根据经验,当我在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不会通知你这个语法错误。

将小写字母转换为大写字母:

str1 = "Hello How are U"

new_str = " "

for i in str1:

        if str1[i].islower():

            new_str = new_str + str1[i].upper()

print(new_str)

错误:

TypeError:字符串索引必须为整数

解决方案:

for i in range(0, len(str1))
// Use range while iterating the string.

如何读取这个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" } } } ]

变量item是一个字符串。索引是这样的:

>>> mystring = 'helloworld'
>>> print mystring[0]
'h'

上面的例子使用字符串的0索引来表示第一个字符。

字符串不能有字符串索引(像字典一样)。所以这行不通:

>>> mystring = 'helloworld'
>>> print mystring['stringindex']
TypeError: string indices must be integers