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.pswp.cn/news/215894.shtml
繁體地址,請注明出處:http://hk.pswp.cn/news/215894.shtml
英文地址,請注明出處:http://en.pswp.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鎖屏頁面時鐘顯…