简单查询类json结构

pson的Python项目详细描述


python库使查询类似json的结构变得简单!

随着返回json的api的激增,使用类似json的结构(即如果使用json并通过json.loads()运行它,您将得到什么)查询这些类型的结构是一个常见的需求。

大多数人要么手动遍历结构,要么编写自己的查询逻辑,这个库旨在通过提供通用的查询实用程序来解决这一需求。它使用点符号以类似于文档数据库(如mongodb)的方式遍历结构。

示例

用以下json示例演示:

json={'header':{'title':'Hello World','year':2014},'body':{'translations':[{'language':'french','translation':'bonjour'},{'language':'german','translation':'guten tag'}]}}

传统(预pson)方法:

>>> json['header']['title']'Hello World'

新的pson方法:

>>> frompsonimportpathqueryaspq>>> pq(json,'header.title')'Hello World'

更多pson示例:

>>> frompsonimportpathqueryaspq>>> pq(json,'header.title')'Hello World'

# as you'd expect it can return sub-structures
>>> pq(json,'body'){'translations': [{'translation': 'bonjour', 'language': 'french'}, {'translation': 'guten tag', 'language': 'german'}]}

# and arrays
>>> pq(json,'body.translations')[{'translation': 'bonjour', 'language': 'french'}, {'translation': 'guten tag', 'language': 'german'}]

# you can query into arrays using numerical indicies
>>> pq(json,'body.translations.0.language')'french'

# you can also not specify an index and get back an array where the rest of the query
# is applied to every element in the array
>>> pq(json,'body.translations.language')['french', 'german']

它如何处理丢失的值?

>>> frompsonimportpathqueryaspq
# by default it returns None rather than throwing an exception
>>> pq(json,'header.author')None

# you can over-ride what it returns though
>>> pq(json,'header.author',missing="Unknown")'Unknown'

# which is useful for situations like where you're building strings and don't want to deal
# with lots of KeyError exceptions
>>> pq(json,'header.title')+' by '+pq(json,'header.author',missing="Unknown")'Hello World by Unknown'

安装

待定

作者

由Imran Ghory(@ImranGhory)建造。根据麻省理工学院的执照被释放。欢迎通过Github投稿。

欢迎加入QQ群-->: 979659372 Python中文网_新手群

推荐PyPI第三方库


热门话题
空字符串检查在java中未按预期工作   JavaSpringWebClient:自动计算主体的HMAC签名并将其作为头传递   foreach是否有一个Java等效的foreach循环和一个引用变量?   java如何在Eclipse中导入jar   使用特定第三方或java时lombok触发错误。*方法或构造函数   安卓 java将对象数组转换为int数组   java使一定百分比的JUnit测试通过   java Android:将Seekbar的一个值与另一个值进行比较   java将int数组(图像数据)写入文件的最佳方式是什么   java取代了系统。yml的构造函数内的getProperty   sqlite Java将公钥和私钥转换为字符串,然后再转换回字符串   安卓获取白色像素并将其保存到java opencv中的数组中   java为什么是ServerSocket。setSocketFactory静态?   Java数组似乎在不直接修改的情况下更改值