JSONPath is an information extraction class library, which is derived from A tool for extracting specified information from JSON documents, providing multiple language implementation versions, including Javascript, Python, PHP and Java.
The installation method of JSONPath is as follows: pip install jsonpath
Comparing JSONPath syntax and XPATH syntax, JSON has a clear structure, high readability, low complexity, and is very easy to match. . The syntax of JSONPath is similar to XPath. The following table shows the syntax comparison between JSONPath and 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 } } }
The variable bookJson is already included This JSON string can be deserialized by the following code to obtain a JSON object:
books=json.loads(bookJson)
1) View the color attribute of the bicycle under the store:
checkurl = "$.store.bicycel.color" print(jsonpath.jsonpath(books, checkurl)) # 输出:['red']
2) Output the content contained in the book node All objects:
checkurl = "$.store.book[*]" object_list=jsonpath.jsonpath(books, checkurl) print(object_list)
3) Output the first object of the book node:
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) Output the attribute title values corresponding to all objects in the book node:
checkurl = "$.store.book[*].title" titles = jsonpath.jsonpath(books, checkurl) print(titles) # 输出: ['Sayings of the Century', 'The Lord of the Rings']
5 ) Output all objects in the book node whose category is 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) Output all objects in the book node whose price is less than 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) Output all objects in the book node that contain 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}]
The above is the detailed content of How to use JsonPath for Python Json read and write operations. For more information, please follow other related articles on the PHP Chinese website!