什么是JSONPath? (What is JSONPath?)

JSONPath is an expression language to parse JSON data. It’s very similar to the XPath expression language to parse XML data.

JSONPath是一种用于解析JSON数据的表达语言。 与解析XML数据的XPath表达式语言非常相似。

The idea is to parse the JSON data and get the value you want. This is more memory efficient because we don’t need to read the complete JSON data.

想法是解析JSON数据并获取所需的值。 由于不需要读取完整的JSON数据,因此内存使用效率更高。

Python JSONPath库 (Python JSONPath Libraries)

There are many JSONPath libraries in Python.

Python中有许多JSONPath库。

  1. jsonpath: It’s a port of the Perl, and JavaScript versions of JSONPath.jsonpath :这是Perl和JSONPathJavaScript版本的端口。
  2. jsonpath-rw: The complete Python implementation of the JSONPath expressions. The JSONPath expressions are first class objects, easy to analyze, transform, parse, print, and extend. The jsonpath-rw-ext module provides some additional extensions to extend its functionalities.jsonpath-rw :JSONPath表达式的完整Python实现。 JSONPath表达式是一流的对象,易于分析,转换,解析,打印和扩展。 jsonpath-rw-ext模块提供了一些其他扩展,以扩展其功能。
  3. jsonpath-ng: The final implementation of the JSONPath that aims to be standard compliant, including arithmetic and binary comparison operators. This library merges jsonpath-rw and jsonpath-rw-ext modules and further enhances it.jsonpath-ng : JSONPath的最终实现,旨在实现标准兼容,包括算术和二进制比较运算符。 该库合并了jsonpath-rw和jsonpath-rw-ext模块,并对其进行了进一步增强。

使用哪个Python JSONPath库? (Which Python JSONPath Library to Use?)

The jsonpath-ng module is the most comprehensive and written purely in Python. It supports both Python 2 and Python 3. So, we will use this module for Python JSONPath examples.

jsonpath-ng模块是最全面的模块, 仅用 Python编写。 它同时支持Python 2和Python3。因此,我们将该模块用于Python JSONPath示例。

安装jsonpath-ng模块 (Installing jsonpath-ng Module)

We can install jsonpath-ng module using PIP.

我们可以使用PIP安装jsonpath-ng模块。

$ pip3.7 install jsonpath-ng

Python jsonpath-ng Install

Python jsonpath-ng安装

使用JSONPath解析简单的JSON数据 (Parsing a Simple JSON Data using JSONPath)

Let’s look at a simple example to parse the JSON data and get the required attribute value.

让我们看一个简单的示例,解析JSON数据并获取所需的属性值。

import jsonfrom jsonpath_ng import jsonpath, parsejson_string = '{"id":1, "name":"Pankaj"}'
json_data = json.loads(json_string)jsonpath_expression = parse('$.id')match = jsonpath_expression.find(json_data)print(match)
print("id value is", match[0].value)

Output:

输出

[DatumInContext(value=1, path=Fields('id'), context=DatumInContext(value={'id': 1, 'name': 'Pankaj'}, path=Root(), context=None))]
id value is 1

We are using json module to convert the JSON string to a dictionary.

我们正在使用json模块将JSON字符串转换为字典 。

使用JSONPath表达式解析列表 (Parsing a List using JSONPath Expression)

The JSON key can contain a list of values. We can use JSONPath expression to parse the list and get the list of values.

JSON密钥可以包含值列表。 我们可以使用JSONPath表达式来解析列表并获取值列表。

Let’s say we have a JSON file “db.json” with the following contents.

假设我们有一个包含以下内容的JSON文件“ db.json”。

{"employees": [{"id": 1,"name": "Pankaj","salary": "10000"},{"name": "David","salary": "5000","id": 2}]
}

We want to parse this JSON file and get the list of employee ids. We can use JSONPath expressions to get this data very easily.

我们要解析此JSON文件并获取员工ID列表。 我们可以使用JSONPath表达式非常轻松地获取此数据。

import json
from jsonpath_ng import jsonpath, parsewith open("db.json", 'r') as json_file:json_data = json.load(json_file)print(json_data)jsonpath_expression = parse('employees[*].id')for match in jsonpath_expression.find(json_data):print(f'Employee id: {match.value}')

Output:

输出:

{'employees': [{'id': 1, 'name': 'Pankaj', 'salary': '10000'}, {'name': 'David', 'salary': '5000', 'id': 2}]}
Employee id: 1
Employee id: 2
Python f-strings – PEP 498 – Literal String InterpolationPython f字符串– PEP 498 –文字字符串插值

If you want to get the data into a list, you can use Python list comprehension.

如果要将数据放入列表中,可以使用Python list comprehension 。

emp_ids_list = [match.value for match in jsonpath_expression.find(json_data)]
print(emp_ids_list)  # [1, 2]

结论 (Conclusion)

JSONPath provides us an easy way to parse the JSON data and extract specific values. It’s very useful when the JSON data is huge and we are interested in only few of the values.

JSONPath为我们提供了一种解析JSON数据并提取特定值的简便方法。 当JSON数据庞大且我们仅对其中几个值感兴趣时,此功能非常有用。

参考资料 (References)

  • jsonpath.com: to test the JSONPath expression validityjsonpath.com :测试JSONPath表达式的有效性
  • jsonlint.com: to validate JSON datajsonlint.com :验证JSON数据

翻译自: https://www.journaldev.com/33265/python-jsonpath-examples

Python JSONPath示例相关推荐

  1. python把桢写入txt_ffmpeg 常用参数一览表及python 使用示例

    FFmpeg是一套可以用来记录.转换数字音频.视频,并能将其转化为流的开源计算机程序.提供了录制.转换以及流化音视频的完整解决方案. 它包含了非常先进的音频/视频编解码库libavcodec,这里介绍 ...

  2. python函数示例_PHP closeir()函数与示例

    python函数示例 PHP Closedir()函数 (PHP closedir() function) The full form of closedir is "Close Direc ...

  3. python函数示例_带Python示例的complex()函数

    python函数示例 Python complex()函数 (Python complex() function) complex() function is a library function i ...

  4. python函数示例_带Python示例的float()函数

    python函数示例 Python float()函数 (Python float() function) float() function is a library function in Pyth ...

  5. python函数示例_使用Python中的示例的input()函数

    python函数示例 Python input()函数 (Python input() function) input() function is a library function, it is ...

  6. Python MySQL示例教程

    Welcome to Python MySQL example tutorial. MySQL is one of the most widely used database and python p ...

  7. python编程示例_Python套接字编程–服务器,客户端示例

    python编程示例 Good Day Learners! In our previous tutorial, we discussed about Python unittest module. T ...

  8. python代码设置超参数_超参数调优总结,贝叶斯优化Python代码示例

    本文介绍超参数(hyperparameter)的调优方法. 神经网络模型的参数可以分为两类,模型参数,在训练中通过梯度下降算法更新: 超参数,在训练中一般是固定数值或者以预设规则变化,比如批大小(ba ...

  9. python jsonpath模块

    jsonpath jsonpath第三方模块.jsonpath是json的XPath工具,简单说就是从 字典对象 中查找数据更方便,可以解析多层嵌套的json数据. 不使用jsonpath时查询 字典 ...

最新文章

  1. 均匀分布取某一点概率_概率和概率分布
  2. java 精确 计算_java中进行高精度精准计算
  3. java高级特性2,Java高级特性 2
  4. ORB-SLAM2和ORB-SLAM的区别
  5. Swift @escaping @noescape
  6. vsftpd安装配置_vsftpd上传文件大小为0(主动模式)
  7. 计算机图形学全代码,计算机图形学作业参考代码
  8. 借Java EE守护者联盟之力拯救Java EE
  9. hive select 语句
  10. turf.js字典——查询turf库的所有方法及用途
  11. STM32内部RAM在线调试配置方法及详细说明(基于Keil开发工具)
  12. 安卓手机卸载手机自带软件(adb)
  13. vue页面换成手机适配屏幕
  14. 华为 GaussDB 数据库十问
  15. 使用Photoshop2022给图片制作出精彩的渐变效果
  16. Muli3D 1 下载与编译
  17. bilinear 神经网络_基于多尺度双线性卷积神经网络的多角度下车型精细识别
  18. (九)隐私计算--安全多方计算
  19. 集群qorum数量master-eligible节点掉线解决方法
  20. gem5和NVM的搭建(完整版)

热门文章

  1. [bzoj1834][ZJOI2010]network 网络扩容
  2. Python写入文件,但是发现文件为空,竟然未写入!
  3. android ListView 自动滚动到最底部
  4. asp.net 导出word文档
  5. [转载] pandas dataframe 提取行和列
  6. Spring的@Transactional事务注意事项
  7. 题解-Codeforces671D Roads in Yusland
  8. MyBatis数据库连接的基本使用-补充Mapper映射器
  9. 第一次作业+105032014142
  10. String写时拷贝实现