jsonpath:使用Python处理JSON数据

使用Python处理JSON数据

25.1 JSON简介

25.1.1 什么是JSON

    JSON全称为JavaScript Object Notation,一般翻译为JS标记,是一种轻量级的数据交换格式。是基于ECMAScript的一个子集,采用完全独立于编程语言的文本格式来存储和表示数据。简洁和清晰的层次结构使得JSON成为理想的数据交换语言,其主要特点有:易于阅读易于机器生成有效提升网络速度等。

25.1.2 JSON的两种结构

    JSON简单来说,可以理解为JavaScript中的数组对象,通过这两种结构,可以表示各种复杂的结构。

25.1.2.1 数组

    数组在JavaScript是使用中括号[ ]来定义的,一般定义格式如下所示:

let array=["Surpass","28","Shanghai"];

    若要对数组取值,则需要使用索引。元素的类型可以是数字字符串数组对象等。

25.1.2.2 对象

    对象在JavaScript是使用大括号{ }来定义的,一般定义格式如下所示:

let personInfo={name:"Surpass",age:28,location:"Shanghai"
}

    对象一般是基于keyvalue,在JavaScript中,其取值方式也非常简单variable.key即可。元素value的类型可以是数字字符串数组对象等。

25.1.3 支持的数据格式

    JSON支持的主要数据格式如下所示:

  • 数组:使用中括号
  • 对象:使用大括号
  • 整型浮点型布尔类型null
  • 字符串类型:必须使用双引号,不能使用单引号

    多个数据之间使用逗号做为分隔符,基与Python中的数据类型对应表如下所示:

JSONPython
Objectdict
arraylist
stringstr
number(int)int
number(real)float
trueTrue
falseFalse
nullNone

25.2 Python对JSON的支持

25.2.1 Python 和 JSON 数据类型

    在Python中主要使用json模块来对JSON数据进行处理。在使用前,需要导入json模块,用法如下所示:

import json

    json模块中主要包含以下四个操作函数,如下所示:

    在json的处理过种中,Python中的原始类型与JSON类型会存在相互转换,具体的转换表如下所示:

  • Python 转换为 JSON
PythonJSON
dictObject
listarray
tuplearray
strstring
intnumber
floatnumber
Truetrue
Falsefalse
Nonenull
  • JSON 转换为 Python
JSONPython
Objectdict
arraylist
stringstr
number(int)int
number(real)float
trueTrue
falseFalse
nullNone
25.2.2 json模块常用方法

    关于Python 内置的json模块,可以查看之前我写的文章:https://www.cnblogs.com/surpassme/p/13034972.html

25.3 使用JSONPath处理JSON数据

    内置的json模块,在处理简单的JSON数据时,易用且非常非常方便,但在处理比较复杂且特别大的JSON数据,还是有一些费力,今天我们使用一个第三方的工具来处理JSON数据,叫JSONPath

25.3.1 什么是JSONPath

    JSONPath是一种用于解析JSON数据的表达语言。经常用于解析和处理多层嵌套的JSON数据,其用法与解析XML数据的XPath表达式语言非常相似。

25.3.2 安装

    安装方法如下所示:

# pip install -U jsonpath
25.3.3 JSONPath语法

    JSONPath语法与XPath非常相似,其对应参照表如下所示:

XPathJSONPath描述
/$根节点/元素
.@当前节点/元素
/. or []子元素
..n/a父元素
//..递归向下搜索子元素
**通配符,表示所有元素
@n/a访问属性,JSON结构的数据没有这种属性
[][]子元素操作符(可以在里面做简单的迭代操作,如数据索引,根据内容选值等)
|[,]支持迭代器中做多选
n/a[start :end :step]数组分割操作
[]?()筛选表达式
n/a()支持表达式计算
()n/a分组,JSONPath不支持

以上内容可查阅官方文档:JSONPath - XPath for JSON

    我们以下示例数据为例,来进行对比,如下所示:

{ "store": {"book": [ { "category": "reference","author": "Nigel Rees","title": "Sayings of the Century","price": 8.95},{ "category": "fiction","author": "Evelyn Waugh","title": "Sword of Honour","price": 12.99},{ "category": "fiction","author": "Herman Melville","title": "Moby Dick","isbn": "0-553-21311-3","price": 8.99},{ "category": "fiction","author": "J. R. R. Tolkien","title": "The Lord of the Rings","isbn": "0-395-19395-8","price": 22.99}],"bicycle": {"color": "red","price": 19.95}}
}
XPathJSONPath结果
/store/book/author$.store.book[*].author获取book节点中所有author
//author$..author获取所有author
/store/*$.store.*获取store的元素,包含book和bicycle
/store//price$.store..price获取store中的所有price
//book[3]$..book[2]获取第三本书所有信息
//book[last()]..����[(@.�����ℎ−1)]..book[-1:]获取最后一本书的信息
//book[position()❤️]..����[0,1]..book[:2]获取前面的两本书
//book[isbn]$..book[?(@.isbn)]根据isbn进行过滤
//book[price<10]$..book[?(@.price<10)]根据price进行筛选
//*$..*所有元素

在XPath中,下标是1开始,而在JSONPath中是从0开始

JSONPath在线练习网址:JSONPath Online Evaluator

25.3.4 JSONPath用法

    其基本用法形式如下所示:

jsonPath(obj, expr [, args])

    基参数如下所示:

  • obj (object|array):

    JSON数据对象

  • expr (string):

    JSONPath表达式

  • args (object|undefined):

    改变输出格式,比如是输出是值还是路径,

args.resultType可选的输出格式为:"VALUE"、"PATH"、"IPATH"

  • 返回类型为(array|false):

    若返回array,则代表成功匹配到数据,false则代表未匹配到数据。

25.3.5 在Python中的使用
from jsonpath import  jsonpath
import jsondata = {"store":{"book": [{"category": "reference","author": "Nigel Rees","title": "Sayings of the Century","price": 8.95},{"category": "fiction","author": "Evelyn Waugh","title": "Sword of Honour","price": 12.99},{"category": "fiction","author": "Herman Melville","title": "Moby Dick","isbn": "0-553-21311-3","price": 8.99},{"category": "fiction","author": "J. R. R. Tolkien","title": "The Lord of the Rings","isbn": "0-395-19395-8","price": 22.99}],"bicycle": {"color": "red","price": 19.95}}
}#  获取book节点中所有author
getAllBookAuthor=jsonpath(data,"$.store.book[*].author")
print(f"getAllBookAuthor is :{json.dumps(getAllBookAuthor,indent=4)}")
#  获取book节点中所有author
getAllAuthor=jsonpath(data,"$..author")
print(f"getAllAuthor is {json.dumps(getAllAuthor,indent=4)}")
#  获取store的元素,包含book和bicycle
getAllStoreElement=jsonpath(data,"$.store.*")
print(f"getAllStoreElement is {json.dumps(getAllStoreElement,indent=4)}")
# 获取store中的所有price
getAllStorePriceA=jsonpath(data,"$[store]..price")
getAllStorePriceB=jsonpath(data,"$.store..price")
print(f"getAllStorePrictA is {getAllStorePriceA}\ngetAllStorePriceB is {getAllStorePriceB}")
# 获取第三本书所有信息
getThirdBookInfo=jsonpath(data,"$..book[2]")
print(f"getThirdBookInfo is {json.dumps(getThirdBookInfo,indent=4)}")
# 获取最后一本书的信息
getLastBookInfo=jsonpath(data,"$..book[-1:]")
print(f"getLastBookInfo is {json.dumps(getLastBookInfo,indent=4)}")
# 获取前面的两本书
getFirstAndSecondBookInfo=jsonpath(data,"$..book[:2]")
print(f"getFirstAndSecondBookInfo is {json.dumps(getFirstAndSecondBookInfo,indent=4)}")
#  根据isbn进行过滤
getWithFilterISBN=jsonpath(data,"$..book[?(@.isbn)]")
print(f"getWithFilterISBN is {json.dumps(getWithFilterISBN,indent=4)}")
# 根据price进行筛选
getWithFilterPrice=jsonpath(data,"$..book[?(@.price<10)]")
print(f"getWithFilterPrice is {json.dumps(getWithFilterPrice,indent=4)}")
# 所有元素
getAllElement=jsonpath(data,"$..*")
print(f"getAllElement is {json.dumps(getAllElement,indent=4)}")
# 未能匹配到元素时
noMatchElement=jsonpath(data,"$..surpass")
print(f"noMatchElement is {noMatchElement}")
# 调整输出格式
controlleOutput=jsonpath(data,expr="$..author",result_type="PATH")
print(f"controlleOutput is {json.dumps(controlleOutput,indent=4)}")

    最终输出结果如下扬尘:

getAllBookAuthor is :["Nigel Rees","Evelyn Waugh","Herman Melville","J. R. R. Tolkien"
]
getAllAuthor is ["Nigel Rees","Evelyn Waugh","Herman Melville","J. R. R. Tolkien"
]
getAllStoreElement is [[{"category": "reference","author": "Nigel Rees","title": "Sayings of the Century","price": 8.95},{"category": "fiction","author": "Evelyn Waugh","title": "Sword of Honour","price": 12.99},{"category": "fiction","author": "Herman Melville","title": "Moby Dick","isbn": "0-553-21311-3","price": 8.99},{"category": "fiction","author": "J. R. R. Tolkien","title": "The Lord of the Rings","isbn": "0-395-19395-8","price": 22.99}],{"color": "red","price": 19.95}
]
getAllStorePrictA is [8.95, 12.99, 8.99, 22.99, 19.95]
getAllStorePriceB is [8.95, 12.99, 8.99, 22.99, 19.95]
getThirdBookInfo is [{"category": "fiction","author": "Herman Melville","title": "Moby Dick","isbn": "0-553-21311-3","price": 8.99}
]
getLastBookInfo is [{"category": "fiction","author": "J. R. R. Tolkien","title": "The Lord of the Rings","isbn": "0-395-19395-8","price": 22.99}
]
getFirstAndSecondBookInfo is [{"category": "reference","author": "Nigel Rees","title": "Sayings of the Century","price": 8.95},{"category": "fiction","author": "Evelyn Waugh","title": "Sword of Honour","price": 12.99}
]
getWithFilterISBN is [{"category": "fiction","author": "Herman Melville","title": "Moby Dick","isbn": "0-553-21311-3","price": 8.99},{"category": "fiction","author": "J. R. R. Tolkien","title": "The Lord of the Rings","isbn": "0-395-19395-8","price": 22.99}
]
getWithFilterPrice is [{"category": "reference","author": "Nigel Rees","title": "Sayings of the Century","price": 8.95},{"category": "fiction","author": "Herman Melville","title": "Moby Dick","isbn": "0-553-21311-3","price": 8.99}
]
getAllElement is [{"book": [{"category": "reference","author": "Nigel Rees","title": "Sayings of the Century","price": 8.95},{"category": "fiction","author": "Evelyn Waugh","title": "Sword of Honour","price": 12.99},{"category": "fiction","author": "Herman Melville","title": "Moby Dick","isbn": "0-553-21311-3","price": 8.99},{"category": "fiction","author": "J. R. R. Tolkien","title": "The Lord of the Rings","isbn": "0-395-19395-8","price": 22.99}],"bicycle": {"color": "red","price": 19.95}},[{"category": "reference","author": "Nigel Rees","title": "Sayings of the Century","price": 8.95},{"category": "fiction","author": "Evelyn Waugh","title": "Sword of Honour","price": 12.99},{"category": "fiction","author": "Herman Melville","title": "Moby Dick","isbn": "0-553-21311-3","price": 8.99},{"category": "fiction","author": "J. R. R. Tolkien","title": "The Lord of the Rings","isbn": "0-395-19395-8","price": 22.99}],{"color": "red","price": 19.95},{"category": "reference","author": "Nigel Rees","title": "Sayings of the Century","price": 8.95},{"category": "fiction","author": "Evelyn Waugh","title": "Sword of Honour","price": 12.99},{"category": "fiction","author": "Herman Melville","title": "Moby Dick","isbn": "0-553-21311-3","price": 8.99},{"category": "fiction","author": "J. R. R. Tolkien","title": "The Lord of the Rings","isbn": "0-395-19395-8","price": 22.99},"reference","Nigel Rees","Sayings of the Century",8.95,"fiction","Evelyn Waugh","Sword of Honour",12.99,"fiction","Herman Melville","Moby Dick","0-553-21311-3",8.99,"fiction","J. R. R. Tolkien","The Lord of the Rings","0-395-19395-8",22.99,"red",19.95
]
noMatchElement is False
controlleOutput is ["$['store']['book'][0]['author']","$['store']['book'][1]['author']","$['store']['book'][2]['author']","$['store']['book'][3]['author']"
]

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处:http://www.mzph.cn/news/215894.shtml

如若内容造成侵权/违法违规/事实不符,请联系多彩编程网进行投诉反馈email:809451989@qq.com,一经查实,立即删除!

相关文章

java对二维数组进行排序

一、按行排序&#xff1a; 对二维数组按进行排序&#xff0c;直接调用Arrays.sort就行&#xff1a; private static int [][] sortRows(int[][] arr) {//行排序for (int i 0; i < arr.length; i) {Arrays.sort(arr[i]);}return arr;}二、按列排序&#xff1a; 1.使用比较…

计算机网络:应用层(一)

我最近开了几个专栏&#xff0c;诚信互三&#xff01; > |||《算法专栏》&#xff1a;&#xff1a;刷题教程来自网站《代码随想录》。||| > |||《C专栏》&#xff1a;&#xff1a;记录我学习C的经历&#xff0c;看完你一定会有收获。||| > |||《Linux专栏》&#xff1…

鸿蒙开发之状态管理@Observed和@ObjectLink

一、使用场景 当对象内引用对象&#xff0c;改变内部对象属性的时候其他状态管理如State、Provide、Consume等是无法触发更新的。同样&#xff0c;在数组内如果有对象&#xff0c;改变对象的属性也是无法更新的。在这种情况下就可以采用Observed和ObjectLink装饰器了。 二、使…

C# WPF上位机开发(简易图像处理软件)

【 声明&#xff1a;版权所有&#xff0c;欢迎转载&#xff0c;请勿用于商业用途。 联系信箱&#xff1a;feixiaoxing 163.com】 图像处理是工业生产重要的环节。不管是定位、测量、检测还是识别&#xff0c;图像处理在工业生产中扮演重要的角色。而c#由于自身快速开发的特点&a…

玩转 Go 语言并发编程:Goroutine 实战指南

一、goroutine 池 本质上是生产者消费者模型在工作中我们通常会使用可以指定启动的 goroutine 数量-worker pool 模式&#xff0c;控制 goroutine 的数量&#xff0c;防止 goroutine 泄漏和暴涨一个简易的 work pool 示例代码如下&#xff1a; package mainimport ("fmt…

小程序跳转tabbar,tabbar页面不刷新

文章地址&#xff1a;12.小程序 之切换到tabBar页面不刷新问题_360问答 解决办法备份&#xff1a; wx.switchTab&#xff1a;跳转到 tabBar 页面&#xff0c;并关闭其他所有非 tabBar 页面 wx.reLaunch&#xff1a;关闭所有页面&#xff0c;打开到应用内的某个页面。 wx.reLa…

解决微信小程序中 ‘nbsp;‘ 空格不生效的问题

在微信小程序开发中&#xff0c;我们经常会使用 来表示一个空格。这是因为在 HTML 中&#xff0c;空格会被解析为一个普通字符&#xff0c;而不会产生实际的空白间距。而 是一种特殊的字符实体&#xff0c;它被解析为一个不可见的空格&#xff0c;可以在页面上产生真正的空…

力扣70. 爬楼梯

动态规划 思路&#xff1a; 使用递归比较容易理解&#xff0c; f(n) f(n - 1) f(n - 2)&#xff1b; 到剩余1级台阶有 f(n - 1)&#xff0c;到剩余2级台阶有 f(n-2)&#xff1b;边界情况是 n 0, f(0) 1n 1, f(1) 1n 2, f(2) 2 递归代码实现&#xff1a; class Soluti…

Axure RP 9 入门教程

1. Axure简介 Axure 是一个交互式原型设计工具&#xff0c;可以帮助用户创建复杂的交互式应用程序和网站。Axure 能够让用户快速构建出具有高度可交互性的原型&#xff0c;可以在团队中进行协作、分享和测试。 使用 Axure 可以设计出各种不同类型的原型&#xff0c;包括网站、移…

系列十五、搭建redis集群

一、概述 上篇文章介绍了redis集群的相关知识&#xff0c;本章实战演示redis的集群环境的详细搭建步骤。如果帮助到了你&#xff0c;请点赞 收藏 关注&#xff01;有疑问的话也可以评论区交流。 二、搭建步骤 2.1、预备知识 判断一个集群中的节点是否可用&#xff0c;是集群…

【SpringBoot篇】详解基于Redis实现短信登录的操作

文章目录 &#x1f970;前言&#x1f6f8;StringRedisTemplate&#x1f339;使用StringRedisTemplate⭐常用的方法 &#x1f6f8;为什么我们要使用Redis代替Session进行登录操作&#x1f386;具体使用✨编写拦截器✨配置拦截器&#x1f33a;基于Redis实现发送手机验证码操作&am…

EarCMS 前台任意文件上传漏洞复现

0x01 产品简介 EarCMS是一个APP内测分发系统的平台。 0x02 漏洞概述 EarCMS前台put_upload.php中,存在pw参数硬编码问题,同时sql语句pdo使用错误,没有有效过滤sql语句,可以控制文件名和后缀,导致可以任意文件上传。 0x03 复现环境 FOFA:app="EearCMS" 0x0…

Flutter实现自定义二级列表

在Flutter开发中&#xff0c;其实系统已经给我们提供了一个可靠的二级列表展开的API&#xff08;ExpansionPanelList&#xff09;&#xff0c;我们先看系统的二级列表展开效果&#xff0c;一次只能展开一个&#xff0c;用ExpansionPanelList.radio实现 由此可见&#xff0c;已经…

容器化升级对服务有哪些影响?

容器技术是近几年计算机领域的热门技术&#xff0c;特别是随着各种云服务的发展&#xff0c;越来越多的服务运行在以 Docker 为代表的容器之内。 本文我们就来分享一下容器化技术相关的知识。 容器化技术简介 相比传统虚拟化技术&#xff0c;容器技术是一种更加轻量级的操作…

分治法求最大子列和

给定N个整数的序列{ A1, A2, …, AN}&#xff0c;其中可能有正数也可能有负数&#xff0c;找出其中连续的一个子数列&#xff08;不允许空序列&#xff09;&#xff0c;使它们的和尽可能大&#xff0c;如果是负数&#xff0c;则返回0。使用下列函数&#xff0c;完成分治法求最大…

CorelDRAW软件2024版本好用吗?有哪些功能优势

CorelDRAW是一款综合性强大的专业平面设计软件&#xff0c;其功能覆盖了矢量图形设计、高级文字编辑、精细绘图以及多页文档和页面设计。该软件不仅适用于广告设计、包装设计&#xff0c;还广泛应用于出版、网页设计和多媒体制作等多个领域。下面就给大家介绍一下CorelDRAW这款…

0012Java安卓程序设计-ssm记账app

文章目录 **摘要**目 录系统设计5.1 APP端&#xff08;用户功能&#xff09;5.2后端管理员功能模块开发环境 编程技术交流、源码分享、模板分享、网课分享 企鹅&#x1f427;裙&#xff1a;776871563 摘要 网络的广泛应用给生活带来了十分的便利。所以把记账管理与现在网络相…

arkts编译报错-arkts-limited-stdlib错误【Bug已完美解决-鸿蒙开发】

文章目录 项目场景:问题描述原因分析:解决方案:适配指导案例此Bug解决方案总结项目场景: arkts编译报错-arkts-limited-stdlib错误。 我用Deveco studio4.0 beta2开发应用,报arkts-limited-stdlib错误 报错内容为: ERROR: ArKTS:ERROR File: D:/prRevivw/3792lapplica…

[Verilog]用Verilog实现串并转换/并串装换

用Verilog实现串并转换/并串装换 摘要 一、串并转换模块 串转并就是将低3位信号和输入信号一起赋值。因为经过转换后&#xff0c;码元速率会将为原来四分之一&#xff0c;所以设置4分频时钟&#xff0c;将其输出。而并转串就是不断右移&#xff0c;取高位输出。 module serial…

Android 11.0 systemui锁屏页面时钟显示样式的定制功能实现

1.前言 在11.0的系统ROM定制化开发中,在进行systemui的相关开发中,当开机完成后在锁屏页面就会显示时间日期的功能,由于 开发产品的需求要求时间显示周几上午下午接下来就需要对锁屏显示时间日期的相关布局进行分析,然后实现相关功能 效果图如图: 2.systemui锁屏页面时钟显…