Warning: file_get_contents(/data/phpspider/zhask/data//catemap/7/neo4j/3.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 错误:TypeError:字符串索引必须是整数_Python - Fatal编程技术网

Python 错误:TypeError:字符串索引必须是整数

Python 错误:TypeError:字符串索引必须是整数,python,Python,python新手,尝试将json文件转换为csv,并编写了以下代码,但不断出现“TypeError:字符串索引必须是整数”错误。请建议 import json import csv #x= '''open("Test_JIRA.json","r")''' #x = json.load(x) with open('Test_JIRA.json') as jsonfile: x = json.load(jsonfile) f = csv.writer(open("test.csv",

python新手,尝试将json文件转换为csv,并编写了以下代码,但不断出现“TypeError:字符串索引必须是整数”错误。请建议

import json
import csv

#x= '''open("Test_JIRA.json","r")'''
#x = json.load(x)

with open('Test_JIRA.json') as jsonfile:
    x = json.load(jsonfile)

f = csv.writer(open("test.csv", "w"))

# Write CSV Header, If you dont need that, remove this line
f.writerow(["id", "self", "key", "customfield_12608", "customfield_12607"])

for x in x:
    f.writerow([x["id"],
                x["self"],
                x["key"],
                x["fields"]["customfield_12608"],
                x["fields"]["customfield_12607"]
                ])
下面是示例1行输入json文件数据:

{"expand":"schema,names","startAt":0,"maxResults":50,"total":100,"issues":[{"expand":"operations,versionedRepresentations,editmeta,changelog,renderedFields","id":"883568","self":"https://jira.xyz.com/rest/api/2/issue/223568","key":"AI-243","fields":{"customfield_22608":null,"customfield_12637":"2017-10-12T21:46:00.000-0700"}}]}

就我看来,问题就在这里

for x in x:
注意,代码中的
x
是一个
dict
,而不是
列表
。我认为(根据提供的json示例)您需要

for x in x['issues']:
另外,@Reti43在评论中注意到,
x['issues']
中的
dicts
键因元素而异。为了使您的代码更安全,您可以使用
get

for x in x['issues']:
    f.writerow([x.get("id"),
                x.get("self"),
                x.get("key"),
                x.get("fields", {}).get("customfield_12608"),
                x.get("fields", {}).get("customfield_12607")
                ])

请添加输入JSON文件和输出错误,如控制台中所示。请提供完整的回溯。变量名称没有区别,因为循环目标只计算一次。x中x的
失败,因为它正在迭代dict的键(这解释了“字符串索引必须是整数”错误)。你答案的第二部分才是真正重要的(尽管
对于x中的x['issues']
同样有效)。@ekhumro谢谢你的评论,我会更正我的答案。问题正如ekhumro所描述的。然而,当代码试图访问自定义字段键时,仍然会遇到一个令人不快的惊喜,因为它们似乎在不同的问题之间有所不同。另外,仅仅因为
for x in x['issues']
可以工作,并不意味着在循环结束时最后一项不会遮住对象。因此,仍然建议对x['issues]
@kvorbiev中的问题执行
。我认为您可以放心地假设顶级键始终存在(请参阅)。因此,只有自定义字段才需要
get()
。谢谢@kvorbiev,它现在可以正常工作了。谢谢你的帮助。