简体   繁体   English

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

[英]Error: TypeError: string indices must be integers

New to python, trying to convert json file to csv and wrote below code but keep getting "TypeError: string indices must be integers" error. python的新手,尝试将json文件转换为csv并编写了以下代码,但始终收到“ TypeError:字符串索引必须为整数”错误。 Please suggest. 请提出建议。

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"]
                ])

Here is sample 1 row input json file data: 这是示例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"}}]}

As far as I see problem is here 据我所知问题在这里

for x in x:

Note, that x in your code is a dict , not list . 请注意,代码中的xdict ,不是list I think (based on provided json example) you need something like 我认为(基于提供的json示例),您需要类似

for x in x['issues']:

Also, @Reti43 note in comment, that keys of dicts in x['issues'] vary between elements. 另外,@ Reti43在注释中指出, x['issues']dicts键在元素之间有所不同。 To make your code more safe you could use get 为了使您的代码更安全,可以使用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")
                ])

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM