[英]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.