python查询json对象路径

2024-06-16 10:30:01 发布

您现在位置:Python中文网/ 问答频道 /正文

我有一个嵌套的json结构,我使用的是objectpath(python API版本),但是我不知道如何选择和过滤一些信息(更确切地说是结构中的嵌套信息)。

例如。 我想为用户“John”选择操作“reading”的“description”。

JSON格式:

{
    "user": 
    {
            "actions":   
             [
                 {
                 "name": "reading",
                 "description": "blablabla"
                 }
             ]
            "name": "John"
    }
}

代码:

$.user[@.name is 'John' and @.actions.name is 'reading'].actions.description

但它不起作用(空集合,但在我的JSON中不是这样)。 有什么建议吗?


Tags: 用户name版本actionsapi信息jsonis
3条回答

这就是你想做的吗?

import objectpath

data = {
    "user": {
        "actions": {
                "name": "reading",
                "description": "blablabla"
            },
        "name": "John"
    }
}

tree = objectpath.Tree(data)
result = tree.execute("$.user[@.name is 'John'].actions[@.name is 'reading'].description")
for entry in result:
    print entry

输出

blablabla

我必须修复你的JSON。另外,tree.execute返回一个生成器。可以用print result.next()替换for循环,但是for循环看起来更清晰。

import objectpath import *

your_json = {"name": "felix", "last_name": "diaz"}

# This json path will bring all the key-values of your json

your_json_path='$.*'

my_key_values = Tree(your_json).execute(your_json_path)

# If you want to retrieve the name node...then specify it. 
my_name= Tree(your_json).execute('$.name')

# If you want to retrieve a the last_name node...then specify it. 
last_name= Tree(your_json).execute('$.last_name')

我相信你在JSON中遗漏了一个逗号:

{
    "user": 
    {
        "actions": [
            {
                 "name": "reading",
                 "description": "blablabla"
            }
        ],
        "name": "John"
    }
}

假设只有一个“John”,只有一个“reading”活动,则以下查询有效:

$.user[@.name is 'John'].actions[0][@.name is 'reading'][0].description

如果可能有多个“John”s和多个“reading”活动,则以下查询几乎可以工作:

$.user.*[@.name is 'John'].actions..*[@.name is 'reading'].description

我说几乎是,因为如果有其他嵌套字典包含“name”和“description”条目,比如

{
    "user": {
        "actions": [
            {
                "name": "reading",
                "description": "blablabla",
                "nested": {
                    "name": "reading",
                    "description": "broken"
                }
            }
        ],
        "name": "John"
    }
}

要获得正确的查询,需要正确地将查询实现到数组中,https://github.com/adriank/ObjectPath/issues/60

相关问题 更多 >