简体   繁体   English

Python for循环json数据仅在单个数据元素时抛出'TypeError:字符串索引必须为整数'

[英]Python for loop over json data throws 'TypeError: string indices must be integers' only when a single element of data

I've inherited the following code which is working great, apart from when only a single data item is return from the original xml. 除了从原始xml仅返回单个数据项之外,我继承了下面的代码,这些代码非常有用。 When that occurs the following error is thrown: 'TypeError: string indices must be integers' 发生这种情况时,将引发以下错误:'TypeError:字符串索引必须为整数'

 result = xmltodict.parse(get_xml())

 latest_result = result['Response']['Items']['Item']
 myJsonData = json.dumps(latest_result)

 j=  json.loads(myJason)
 print type(j)

 for item in j:
    print (item['Id'])
    print (item['OrderId'])

I have narrowed the change in behaviour to a difference in datatype here: 我在这里将行为的变化缩小到数据类型的不同:

print type(j)

When only a single ['Item'] is returned from the source XML the datatype of j is a 'dict', whilst the rest of the time (greater than one ['Item']) its a 'list'. 当从源XML仅返回单个['Item']时,j的数据类型为'dict',而其余时间(大于一个['Item'])为'列表'。

Hope someone can help. 希望有人能帮忙。

Encoding to JSON then decoding again has nothing to do with your question. 编码为JSON然后再次解码与您的问题无关。 It is a red herring, you can use latest_result and still get the same error. 这是一个红色的鲱鱼,您可以使用latest_result并仍然得到相同的错误。

The result['Response']['Items']['Item'] can evidently be either a list of dictionaries, or a single dictionary. result['Response']['Items']['Item']显然可以是字典列表或单个字典。 When iterating over a list, you'll get contained elements, while iteration over a dictionary gives you the keys. 遍历列表时,您将包含元素,而字典中的迭代将为您提供键。 So your item elements are strings (each a key in the dictionary) and you can't address elements in that string with 'Id' or 'OrderId' . 因此,您的item元素是字符串(每个字典中的键),并且您无法使用'Id''OrderId'来寻址该字符串中的元素。

Test for the type or use exception handling: 测试类型或使用异常处理:

if isinstance(latest_result, dict):
    # just one result, wrap it in a single-element list
    latest_result = [latest_result]

Alternatively, fix up the xmltodict code (which you didn't share or otherwise identify) to always return lists for elements, even when there is just a single one. 或者,修复xmltodict代码(您没有共享或以其他方式标识),以始终返回元素的列表,即使只有一个元素也是如此。

This is a common xmltodict module usage problem. 这是一个常见的xmltodict模块使用问题。 When there is a single child, by default, it makes a dict out of it and not a list with a single item. 当有一个孩子,在默认情况下,它使一个dict出来的,而不是用一个单一的项目清单。 Relevant github issue: 相关的github问题:

To workaround it, one option would be to set the dict_constructor argument: 要解决此问题,一种方法是设置dict_constructor参数:

from collections import defaultdict

xmltodict.parse(xml, dict_constructor=lambda *args, **kwargs: defaultdict(list, *args, **kwargs))

暂无
暂无

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

相关问题 Python 循环:类型错误:字符串索引必须是整数 - Python Loop: TypeError: string indices must be integers 类型错误:使用 Python 解析 Json 时,字符串索引必须是整数错误 - TypeError: string indices must be integers error when parsing Json with Python 类型错误:在 Python 中过滤 JSON 中的值时,字符串索引必须是整数 - TypeError: string indices must be integers when filtering values in a JSON in Python TypeError:通过Python读取JSON时,字符串索引必须为整数 - TypeError: string indices must be integers when read JSON via Python python pandas-解析JSON时发生TypeError:字符串索引必须为整数 - python pandas - TypeError when parsing JSON: string indices must be integers TypeError:在 python 中使用 json 文件时,字符串索引必须是整数 - TypeError: string indices must be integers when using json file in python 类型错误:字符串索引必须是整数 - Python JSON - TypeError: string indices must be integers - Python JSON 类型错误:字符串索引必须是整数 - JSON Python - TypeError: string indices must be integers - JSON Python 使用cleaned_data时出现“ TypeError:字符串索引必须为整数” - “TypeError: string indices must be integers” when using cleaned_data TypeError:尝试使用Python从API提取数据时,字符串索引必须为整数 - TypeError: string indices must be integers when trying to extract data from an API using Python
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM