跳转到主要内容

使用路径表达式从JSON对象获取值

项目描述

https://img.shields.io/pypi/l/json-get.svg https://img.shields.io/github/release/srittau/python-json-get/all.svg https://img.shields.io/pypi/v/json-get.svg https://travis-ci.org/srittau/python-json-get.svg?branch=master

使用路径表达式从JSON对象获取值。可选的类型检查是可能的

>>> from jsonget import json_get, json_get_default, JList
>>> j = {
...     "foo": {"num": 3.4, "s": "Text"},
...     "arr": [10, 20, 30],
... }
>>> json_get(j, "/foo/num")
3.4
>>> json_get(j, "/arr[1]")
20
>>> json_get(j, "/foo/unknown")
Traceback (most recent call last):
    ...
ValueError: JSON path '/foo/unknown' not found

值可以选择性地与以下类型之一进行比较:strintfloatboollistdict。不支持检查空值

>>> json_get(j, "/foo/num", str)
Traceback (most recent call last):
    ...
TypeError: wrong JSON type str != float

float 将匹配任何数字,int 只会匹配没有小数部分的数字

>>> json_get(j, "/foo/num", float)
3.4
>>> json_get(j, "/foo/num", int)
Traceback (most recent call last):
    ...
TypeError: wrong JSON type int != float

此外,还可以检查列表值的类型

>>> json_get(j, "/arr", JList(int))
[10, 20, 30]

json_get_default() 可以在给定的路径不存在时返回默认值

>>> json_get_default(j, "/bar", "default value")
'default value'

项目详情


下载文件

下载适用于您的平台文件。如果您不确定选择哪个,请了解更多关于 安装软件包 的信息。

源分布

此版本没有可用的源分布文件。请参阅 生成分布存档的教程

构建分布

json_get-1.1.1-py3-none-any.whl (6.5 kB 查看哈希)

上传时间: Python 3

支持