python - 类似 Xpath 的嵌套 python 字典查询

标签 python xpath jmespath json-path-expression

有没有办法为嵌套的 Python 字典定义 XPath 类型查询。

类似这样的:

foo = {
  'spam':'eggs',
  'morefoo': {
               'bar':'soap',
               'morebar': {'bacon' : 'foobar'}
              }
   }

print( foo.select("/morefoo/morebar") )

>> {'bacon' : 'foobar'}

我还需要选择嵌套列表;)

这可以通过@jellybean 的解决方案轻松完成:

def xpath_get(mydict, path):
    elem = mydict
    try:
        for x in path.strip("/").split("/"):
            try:
                x = int(x)
                elem = elem[x]
            except ValueError:
                elem = elem.get(x)
    except:
        pass

    return elem

foo = {
  'spam':'eggs',
  'morefoo': [{
               'bar':'soap',
               'morebar': {
                           'bacon' : {
                                       'bla':'balbla'
                                     }
                           }
              },
              'bla'
              ]
   }

print xpath_get(foo, "/morefoo/0/morebar/bacon")

[EDIT 2016] 这个问题和公认的答案是古老的。较新的答案可能比原始答案做得更好。但是我没有测试它们,所以我不会更改接受的答案。

最佳答案

我能确定的最好的库之一,此外,它的开发非常活跃,是从 boto 提取的项目:JMESPath .它有一个非常强大的语法来处理通常需要几页代码来表达的事情。

这里有一些例子:

search('foo | bar', {"foo": {"bar": "baz"}}) -> "baz"
search('foo[*].bar | [0]', {
    "foo": [{"bar": ["first1", "second1"]},
            {"bar": ["first2", "second2"]}]}) -> ["first1", "second1"]
search('foo | [0]', {"foo": [0, 1, 2]}) -> [0]

关于python - 类似 Xpath 的嵌套 python 字典查询,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7320319/

相关文章:

amazon-web-services - AWS RDS : how to get latest snapshot with boto3 and jmespath?

python - 有没有办法将实时流从 azure blob 存储复制到 azure my sql

python - 将一些 python 脚本打包为 Linux 的可执行文件

xpath - 谓词 : how is the expression nodeName ='text' evaluated?

php - 当名称包含特殊字符时如何获取 XML 节点内容?

java - 通过 dom4j XPath 奇怪的行为解析带有 namespace 的 xml

json - 如何在 ansible 剧本中使用 JMESPath 进行排序?

ansible - 在 Ansible 中使用带有starts_with的json_query过滤器时出现JMESPathTypeError

c# - Python.NET - 名称不能为空

python - Pandas :在约束下对每对列应用函数