JSONPath是一種資訊抽取類別庫,是從JSON文件中抽取指定資訊的工具,提供多種語言實作版本,包括Javascript、Python、PHP和Java。
JSONPath的安裝方法如下:pip install jsonpath
JSONPath語法和XPATH語法對比,JSON結構清晰,可讀性高,複雜度低,非常容易匹配。 JSONPath的語法與Xpath類似,如下表所示為JSONPath與XPath語法對比:
bookJson = { "store": { "book":[ { "category": "reference", "author": "Nigel Rees", "title": "Sayings of the Century", "price": 8.95 }, { "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 } } }
變數bookJson中已經包含了這段JSON字串,可透過以下程式碼反序列化得到JSON物件:
books=json.loads(bookJson)
1)查看store下的bicycle的color屬性:
checkurl = "$.store.bicycel.color" print(jsonpath.jsonpath(books, checkurl)) # 输出:['red']
2)輸出book節點中包含的所有物件:
checkurl = "$.store.book[*]" object_list=jsonpath.jsonpath(books, checkurl) print(object_list)
3)輸出book節點的第一個物件:
checkurl = "$.store.book[0]" obj = jsonpath.jsonpath(books, checkurl) print(obj) # 输出: ['category': 'reference', 'author': 'Nigel Rees', 'title': 'Sayings of the Century', 'price': 8.95}]
4)輸出book節點中所有物件對應的屬性title值:
checkurl = "$.store.book[*].title" titles = jsonpath.jsonpath(books, checkurl) print(titles) # 输出: ['Sayings of the Century', 'The Lord of the Rings']
5 )輸出book節點中category為fiction的所有物件:
checkurl = "$.store.book[?(@.category=='fiction')]” books=jsonpath.jsonpath(books, checkurl) print(books) # 输出:[{'category': 'fiction', 'author': 'J. R. R. Tolkien', 'title': 'The Lordof the Rings', 'isbn': '0-395-19395-8', 'price': 22.99}]
6)輸出book節點中所有價格小於10的物件:
checkurl="$.store.book[?(@.price<10)]" books = jsonpath.jsonpath(books, checkurl) print(books) # 输出: [{'category': 'reference', 'author': 'Nigel Rees', 'title':'Sayings of the Century', 'price': 8.95}]
7)輸出book節點中所有含有isb的對象:
checkurl = "$.store.book[?(@.isb)]" books = jsonpath.jsonpath(books,checkurl) print(books) # 输出: [{'category': 'fiction', 'author': 'J. R. R. Tolkien', 'title': 'The Lord of the Rings', 'isbn': '0-395-19395-8', 'price': 22.99}]
以上是Python Json讀寫操作之JsonPath怎麼使用的詳細內容。更多資訊請關注PHP中文網其他相關文章!