Python基礎-25 JSONPath用法

来源:https://www.cnblogs.com/surpassme/archive/2022/08/04/16552633.html
-Advertisement-
Play Games

25 使用Python處理JSON數據 25.1 JSON簡介 25.1.1 什麼是JSON JSON全稱為JavaScript Object Notation,一般翻譯為JS標記,是一種輕量級的數據交換格式。是基於ECMAScript的一個子集,採用完全獨立於編程語言的文本格式來存儲和表示數據。簡 ...


25 使用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中的數據類型對應表如下所示:

JSON Python
Object dict
array list
string str
number(int) int
number(real) float
true True
false False
null None

25.2 Python對JSON的支持

25.2.1 Python 和 JSON 數據類型

    在Python中主要使用json模塊來對JSON數據進行處理。在使用前,需要導入json模塊,用法如下所示:

import json

    json模塊中主要包含以下四個操作函數,如下所示:

    在json的處理過種中,Python中的原始類型與JSON類型會存在相互轉換,具體的轉換表如下所示:

  • Python 轉換為 JSON
Python JSON
dict Object
list array
tuple array
str string
int number
float number
True true
False false
None null
  • JSON 轉換為 Python
JSON Python
Object dict
array list
string str
number(int) int
number(real) float
true True
false False
null None

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非常相似,其對應參照表如下所示:

XPath JSONPath 描述
/ $ 根節點/元素
. @ 當前節點/元素
/ . or [] 子元素
.. n/a 父元素
// .. 遞歸向下搜索子元素
* * 通配符,表示所有元素
@ n/a 訪問屬性,JSON結構的數據沒有這種屬性
[] [] 子元素操作符(可以在裡面做簡單的迭代操作,如數據索引,根據內容選值等)
| [,] 支持迭代器中做多選
n/a [start :end :step] 數組分割操作
[] ?() 篩選表達式
n/a () 支持表達式計算
() n/a 分組,JSONPath不支持

以上內容可查閱官方文檔:https://goessner.net/articles/JsonPath/

    我們以下示例數據為例,來進行對比,如下所示:

{ "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
    }
  }
}
XPath JSONPath 結果
/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()] $..book[(@.length-1)]
$..book[-1:]
獲取最後一本書的信息
//book[position()❤️] $..book[0,1]
$..book[:2]
獲取前面的兩本書
//book[isbn] $..book[?(@.isbn)] 根據isbn進行過濾
//book[price<10] $..book[?(@.price<10)] 根據price進行篩選
//* $..* 所有元素

在XPath中,下標是1開始,而在JSONPath中是從0開始

JSONPath線上練習網址:http://jsonpath.com/

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 json

data = {
    "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']"
]

原文地址:https://www.jianshu.com/p/a69a9cf293bd

本文同步在微信訂閱號上發佈,如各位小伙伴們喜歡我的文章,也可以關註我的微信訂閱號:woaitest,或掃描下麵的二維碼添加關註:

作者: Surpassme

來源: http://www.jianshu.com/u/28161b7c9995/

         http://www.cnblogs.com/surpassme/

聲明:本文版權歸作者所有,歡迎轉載,但未經作者同意必須保留此段聲明,且在文章頁面明顯位置給出 原文鏈接 ,否則保留追究法律責任的權利。如有問題,可發送郵件 聯繫。讓我們尊重原創者版權,共同營造良好的IT朋友圈。


您的分享是我們最大的動力!

-Advertisement-
Play Games
更多相關文章
  • 在實際開發工作中,經常會碰到當select下拉數據過需要做分頁的情況 這裡簡單介紹封裝的一個Pagination-Select組件幾個步驟 封裝的比較簡易,可以根據自己的項目進行改動 /components/Pagination-Select/index.vue <template> <div id ...
  • AG Grid是一個客戶端 JavaScript網格 旨在與框架無關 它不依賴於任何框架 因此可以輕鬆地與任何框架集成 AG Grid支持具有相同API的多個框架 通過為每個框架量身定製的GUI層 獲得更好的開發人員體驗和性能 提供Community及Enterprise兩個版本 其中Enterpr ...
  • 本文將介紹一種巧用 background 配合 backdrop- filter 來構建有趣的透視背景效果的方式。 本技巧源自於一名群友的提問,如何構建如 ElementUI 文檔的一種頂欄背景特效,看看效果: 仔細看,在頁面的的滾動過程中,頂欄的背景不是白色的,也不是毛玻璃效果,而是能夠將背景顆粒 ...
  • ​ sass 運算符雖然沒有像那些編程語言那麼強大,但為了更靈活的輸出css,也增強了一些運算符的功能,例如賦值運算符、等號操作符、比較運算符、邏輯運算符、字元串運算符...等等,接下來就來詳細介紹下這些運算符的基本使用 賦值運算符 賦值運算符就是把一個值賦值給一個變數,通過冒號(:)的方式進行承接 ...
  • 1. 事件起因 最近在做一個關於星座的移動端項目,想實現這樣一個需求,每次切換導航欄NavBar item時,都會使下麵的頁面級組件TodayView更改背景色樣式(如圖1到圖2,導航欄從雙魚座切換到處女座,下麵頁面級組件的背景顏色由黃色切換至粉色)。 圖1 圖2 如果利用傳統的辦法,在點擊事件的事 ...
  • 面向對象是一種軟體開發的編程範式。其概念和應用已超越了程式設計和軟體開發,擴展到如資料庫系統、互動式界面、應用結構、應用平臺、分散式系統、網路管理結構、CAD 技術、人工智慧等領域。 ...
  • 三、項目實現讀寫分離 實現方式跟同一個目錄下的01-讀寫分離測試案例基本一致,只不過是將資料庫替換成了項目使用的資料庫 ==同時還有非常重要的一點,ShardingSphere-JDBC的作用不止是讀寫分離,更重要的是其能通過配置文件配置指定演算法,可以自動化的完成對資料庫進行分庫分表操作,且不需要更 ...
  • 一、string 成員函數大全 構造 string()//構造空字元串 string(const char* s);//拷貝s所指向的字元串序列 string(const char* s, size_t n);//拷貝s所指向的字元串序列的第n個到結尾的字元 string(size_t n, cha ...
一周排行
    -Advertisement-
    Play Games
  • GoF之工廠模式 @目錄GoF之工廠模式每博一文案1. 簡單說明“23種設計模式”1.2 介紹工廠模式的三種形態1.3 簡單工廠模式(靜態工廠模式)1.3.1 簡單工廠模式的優缺點:1.4 工廠方法模式1.4.1 工廠方法模式的優缺點:1.5 抽象工廠模式1.6 抽象工廠模式的優缺點:2. 總結:3 ...
  • 新改進提供的Taurus Rpc 功能,可以簡化微服務間的調用,同時可以不用再手動輸出模塊名稱,或調用路徑,包括負載均衡,這一切,由框架實現並提供了。新的Taurus Rpc 功能,將使得服務間的調用,更加輕鬆、簡約、高效。 ...
  • 本章將和大家分享ES的數據同步方案和ES集群相關知識。廢話不多說,下麵我們直接進入主題。 一、ES數據同步 1、數據同步問題 Elasticsearch中的酒店數據來自於mysql資料庫,因此mysql數據發生改變時,Elasticsearch也必須跟著改變,這個就是Elasticsearch與my ...
  • 引言 在我們之前的文章中介紹過使用Bogus生成模擬測試數據,今天來講解一下功能更加強大自動生成測試數據的工具的庫"AutoFixture"。 什麼是AutoFixture? AutoFixture 是一個針對 .NET 的開源庫,旨在最大程度地減少單元測試中的“安排(Arrange)”階段,以提高 ...
  • 經過前面幾個部分學習,相信學過的同學已經能夠掌握 .NET Emit 這種中間語言,並能使得它來編寫一些應用,以提高程式的性能。隨著 IL 指令篇的結束,本系列也已經接近尾聲,在這接近結束的最後,會提供幾個可供直接使用的示例,以供大伙分析或使用在項目中。 ...
  • 當從不同來源導入Excel數據時,可能存在重覆的記錄。為了確保數據的準確性,通常需要刪除這些重覆的行。手動查找並刪除可能會非常耗費時間,而通過編程腳本則可以實現在短時間內處理大量數據。本文將提供一個使用C# 快速查找並刪除Excel重覆項的免費解決方案。 以下是實現步驟: 1. 首先安裝免費.NET ...
  • C++ 異常處理 C++ 異常處理機制允許程式在運行時處理錯誤或意外情況。它提供了捕獲和處理錯誤的一種結構化方式,使程式更加健壯和可靠。 異常處理的基本概念: 異常: 程式在運行時發生的錯誤或意外情況。 拋出異常: 使用 throw 關鍵字將異常傳遞給調用堆棧。 捕獲異常: 使用 try-catch ...
  • 優秀且經驗豐富的Java開發人員的特征之一是對API的廣泛瞭解,包括JDK和第三方庫。 我花了很多時間來學習API,尤其是在閱讀了Effective Java 3rd Edition之後 ,Joshua Bloch建議在Java 3rd Edition中使用現有的API進行開發,而不是為常見的東西編 ...
  • 框架 · 使用laravel框架,原因:tp的框架路由和orm沒有laravel好用 · 使用強制路由,方便介面多時,分多版本,分文件夾等操作 介面 · 介面開發註意欄位類型,欄位是int,查詢成功失敗都要返回int(對接java等強類型語言方便) · 查詢介面用GET、其他用POST 代碼 · 所 ...
  • 正文 下午找企業的人去鎮上做貸後。 車上聽同事跟那個司機對罵,火星子都快出來了。司機跟那同事更熟一些,連我在內一共就三個人,同事那一手指桑罵槐給我都聽愣了。司機也是老社會人了,馬上聽出來了,為那個無辜的企業經辦人辯護,實際上是為自己辯護。 “這個事情你不能怪企業。”“但他們總不能讓銀行的人全權負責, ...