首页 > 解决方案 > TypeError:字符串索引必须是整数,而其他索引必须是 JSON 集合

问题描述

在 Python 中加载 json 集合时,我发现当集合中可能有 0、1 或多个项目并且 python 在找不到对象、字典对象和字典列表之间切换时会发生许多问题。环顾四周,我看到代码试图以各种方式处理这个问题,但并没有真正找到一个通用的解决方案,我认为,当项目数量可变时,这一定是一个相当普遍的问题。

现有的建议似乎以 if ... elif ... else 处理 json 对象而告终,但是每次处理对象时这样做真的很麻烦,因为您以在多个代码分支中处理对象的代码结束。

标签: pythonjsoncollections

解决方案


经过一番摸索,我想出了以下模式来解决这个问题,并且如果集合中有 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 或许多项目。


推荐阅读