V2EX = way to explore
V2EX 是一个关于分享和探索的地方
现在注册
已注册用户请  登录
推荐学习书目
Learn Python the Hard Way
Python Sites
PyPI - Python Package Index
http://diveintopython.org/toc/index.html
Pocoo
值得关注的项目
PyPy
Celery
Jinja2
Read the Docs
gevent
pyenv
virtualenv
Stackless Python
Beautiful Soup
结巴中文分词
Green Unicorn
Sentry
Shovel
Pyflakes
pytest
Python 编程
pep8 Checker
Styles
PEP 8
Google Python Style Guide
Code Style from The Hitchhiker's Guide
keroppi
V2EX  ›  Python

Python 如何搜索 hash/list 中的 json 数据

  •  
  •   keroppi · 2021-11-04 16:46:26 +08:00 · 2056 次点击
    这是一个创建于 875 天前的主题,其中的信息可能已经有所发展或是发生改变。
    hash 的结构示例:

    key: users
    name: openid
    value: json.dumps({ status: 2})

    怎么快速搜索例如 users.xxxx.status == 2 这种条件的数据?
    7 条回复    2021-11-21 18:37:01 +08:00
    Zhuzhuchenyan
        1
    Zhuzhuchenyan  
       2021-11-04 17:36:13 +08:00
    开箱即用的方法应该是不存在的。
    要想避免 O(n)的查询复杂度的话,万变不离其宗的方法就是加索引,比较简单的就是加个对于 status 的倒排索引

    倒排索引的 key 就是 status 的值,如下例子
    [1] => {user1, user2, ...}
    [2] => {user3, user4, .....}
    imn1
        2
    imn1  
       2021-11-04 18:10:04 +08:00
    1.网上有 nested dict 2 1dim 或者 flatten dict 的代码,我忘了出处了,搜搜吧
    转为一维后就容易搜了

    2.如果已经知道“路径”,有个包叫 jsonpath ,用类似 xpath 方式搜索 json

    3.types 有个类 Simplenamespace ,把 dict[key] 转为 dict.key 形式,不过只能转一层,嵌套就自己写个递归吧

    4. json 是字符串,可用正则,这是另类思维
    MoYi123
        3
    MoYi123  
       2021-11-04 19:38:14 +08:00
    我有点看不懂你举的例子是怎么样一个数据结构.

    python3.10 出的模式匹配,应该能用来做这个.
    MoYi123
        4
    MoYi123  
       2021-11-04 19:45:38 +08:00
    objs = [
    ____{"key": "users", "value": {"status": 2}, "name": "openid"},
    ____{"key": "users", "value": {"status": 3}, "name": "openid"}
    ]
    for obj in objs:
    ____match obj:
    ________case {"value": {"status": 2}}:
    ____________print(obj)
    ClericPy
        5
    ClericPy  
       2021-11-04 21:02:43 +08:00
    如果猜错了, 那就当我没说

    排名有先后
    jmespath
    objectpath
    jsonpath-rw
    Jsonpath
    dongcidaci
        6
    dongcidaci  
       2021-11-05 12:26:31 +08:00 via Android
    递归,dfs
    shm7
        7
    shm7  
       2021-11-21 18:37:01 +08:00
    如果格式固定,为什么不试试 named tuple
    关于   ·   帮助文档   ·   博客   ·   API   ·   FAQ   ·   我们的愿景   ·   实用小工具   ·   2635 人在线   最高记录 6543   ·     Select Language
    创意工作者们的社区
    World is powered by solitude
    VERSION: 3.9.8.5 · 26ms · UTC 15:50 · PVG 23:50 · LAX 08:50 · JFK 11:50
    Developed with CodeLauncher
    ♥ Do have faith in what you're doing.