如何解析 json 以获取数组中特定键的所有值?

新手上路,请多包涵

我在尝试使用 python 从 json 数组中的特定键获取值列表时遇到问题。使用下面的 JSON 示例,我试图创建一个仅包含 name 键值的列表。原始 JSON:

 [
    {
        "id": 1,
        "name": "Bulbasaur",
        "type": [
            "grass",
            "poison"
        ]
    },
    {
        "id": 2,
        "name": "Ivysaur",
        "type": [
            "grass",
            "poison"
        ]
    }
]

预期的:

 ["Bulbasaur", "Ivysaur"]

下面是我的方法的代码:

 import json
try:
    with open("./simple.json", 'r') as f:
        contents = json.load(f)
except Exception as e:
    print(e)

print(contents[:]["name"])

我正在尝试采用一种不需要循环每个索引并附加它们的方法,就像上面的代码一样。这种方法可以使用 python 的 json 库吗?

原文由 Radhian Amri 发布,翻译遵循 CC BY-SA 4.0 许可协议

阅读 683
2 个回答

你不能做 contents[:]["name"] 因为 contents 是一个列表是一个带有整数索引的字典,你不能使用字符串访问它的元素 name .

要解决此问题,您需要遍历列表并获取键的值 name 每个 item

 import json
contents = []

try:
    with open("./simple.json", 'r') as f:
        contents = json.load(f)
except Exception as e:
    print(e)

li = [item.get('name') for item in contents]
print(li)

输出将是

['Bulbasaur', 'Ivysaur']

原文由 Devesh Kumar Singh 发布,翻译遵循 CC BY-SA 4.0 许可协议

这不是问题的真正答案。真正的答案是使用列表理解。但是,您 可以 创建一个类,允许您专门使用您在问题中尝试过的语法。一般的想法是对 list 进行子类化,以便像 [:] --- 这样的切片将一个特殊视图(另一个类)返回到列表中。这个特殊视图将允许同时从所有词典中检索和分配。

 class DictView:
    """
    A special class for getting and setting multiple dictionaries
    simultaneously. This class is not meant to be instantiated
    in its own, but rather in response to a slice operation on UniformDictList.
    """
    def __init__(parent, slice):
        self.parent = parent
        self.range = range(*slice.indices(len(parent)))

    def keys(self):
        """
        Retreives a set of all the keys that are shared across all
        indexed dictionaries. This method makes `DictView` appear as
        a genuine mapping type to `dict`.
        """
        key_set = set()
        for k in self.range:
            key_set &= self.parent.keys()
        return key_set

    def __getitem__(self, key):
        """
        Retreives a list of values corresponding to all the indexed
        values for `key` in the parent. Any missing key will raise
        a `KeyError`.
        """
        return [self.parent[k][key] for k in self.range]

    def get(self, key, default=None):
        """
        Retreives a list of values corresponding to all the indexed
        values for `key` in the parent. Any missing key will return
        `default`.
        """
        return [self.parent[k].get(key, default) for k in self.range]

    def __setitem__(self, key, value):
        """
        Set all the values in the indexed dictionaries for `key` to `value`.
        """
        for k in self.range:
            self.parent[k][key] = value

    def update(self, *args, **kwargs):
        """
        Update all the indexed dictionaries in the parent with the specified
        values. Arguments are the same as to `dict.update`.
        """
        for k in self.range:
             self.parent[k].update(*args, **kwargs)

class UniformDictList(list):
    def __getitem__(self, key):
        if isinstance(key, slice):
            return DictView(self, key)
        return super().__getitem__(key)

您的原始代码现在可以开箱即用,只需在 UniformDictList 中添加一层包装即可:

 import json
try:
    with open("./simple.json", 'r') as f:
        contents = UniformDictList(json.load(f))
except Exception as e:
    print(e)

print(contents[:]["name"])

原文由 Mad Physicist 发布,翻译遵循 CC BY-SA 4.0 许可协议

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题