python - TypeError:字符串索引必须是整数,而其他索引必须是 JSON 集合
问题描述
在 Python 中加载 json 集合时,我发现当集合中可能有 0、1 或多个项目并且 python 在找不到对象、字典对象和字典列表之间切换时会发生许多问题。环顾四周,我看到代码试图以各种方式处理这个问题,但并没有真正找到一个通用的解决方案,我认为,当项目数量可变时,这一定是一个相当普遍的问题。
现有的建议似乎以 if ... elif ... else 处理 json 对象而告终,但是每次处理对象时这样做真的很麻烦,因为您以在多个代码分支中处理对象的代码结束。
解决方案
经过一番摸索,我想出了以下模式来解决这个问题,并且如果集合中有 0、1 或许多项目,它似乎可以可靠地工作。
def node_list(d, k) :
"""
handle a collection node in a json object by returning:
an empty list if there are no child nodes at d[k],
or a list with 1 dictionary entry if there is one child node at d[k]
or a list of dictionaries if there are multiple child nodes at d[k]
"""
if d is None : raise Exception("d is None")
if type(d) is not dict : raise Exception("d is not a dict")
if d.get(k) is None : return []
if type(d.get(k)) is dict : return [d.get(k)]
if type(d.get(k)) is not list : raise Exception("d[k] is not a dict or list")
return d.get(k)
处理 json 集合的调用现在如下所示:
import json
root = json.load(open(file,'r', encoding='utf-8-sig'))
for item in node_list(root,'Item') :
# code to handle each item here
pass
现在,如果有 0,1 或许多项目,我会得到一个适当的列表,其中包含 0、1 或许多项目。
推荐阅读
- android - DiffUtil 问题:新旧列表相同
- elasticsearch - ElasticSearch-如何结合不同查询的结果来提高平均精度
- android - 在 API > 24 上显示菜单后隐藏导航栏
- rsyslog - rsyslog 8.34.0:无法加载模块“/usr/lib/rsyslog/omuxsock.so”
- javascript - 如何通过 html 标签将每一行包装在 textarea 中?
- excel - 如何在 cloumn2 中找到 E1 值,然后使用宏替换为 column1 值?
- ms-access - 将子表单保存过程链接到父表单保存按钮
- webpack - Webpack中设置两个环境变量的目的
- qlikview - 过去 12 个月的 QlikView 表达式 & DISTINCT & 未因选择而改变
- spring-boot - Spring Boot 中的 Mockito ElasticSearch 单元测试