更新时间:2021-05-27 来源:黑马程序员 浏览量:
     
JSONPath是一种信息抽取类库,是从JSON文档中抽取指定信息的工具,提供多种语言实现版本,包括Javascript、Python、PHP和Java。
JSONPath的安装方法如下:
pip install jsonpathJSONPath语法和XPATH语法对比 JSON结构清晰,可读性高,复杂度低,非常容易匹配。JSONPath的语法与Xpath类似,如下表所示为JSONPath与XPath语法对比。
| XPATH | JSONPATH | 描述 | 
| / | $ | 根节点 | 
| . | @ | 现行节点 | 
| / | .or[] | 取子节点 | 
| .. | n/a | 取父节点,JSONPath未支持 | 
| // | .. | 不管位置,选择所有符合条件的节点 | 
| * | * | 匹配所有元素节点 | 
| @ | n/a | 根据属性访问,JSON不支持,因为JSON是个key-value递归结构,不需要属性访问 | 
| [] | [] | 迭代器标示(可以在里面做简单的迭代操作,如数组下标、根据内容选值等) | 
| | | [,] | 支持迭代器中做多选 | 
| [] | ?() | 支持过滤操作 | 
| n/a | () | 分组,JSONPath不支持 | 
      
    下面使用一个JSON文档演示JSONPath的具体使用。JSON 文档的内容如下:
{
  "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)
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}]猜你喜欢:
1024首播|39岁程序员逆袭记:不被年龄定义,AI浪潮里再迎春天
2025-10-241024程序员节丨10年同行,致敬用代码改变世界的你
2025-10-24【AI设计】北京143期毕业仅36天,全员拿下高薪offer!黑马AI设计连续6期100%高薪就业
2025-09-19【跨境电商运营】深圳跨境电商运营毕业22个工作日,就业率91%+,最高薪资达13500元
2025-09-19【AI运维】郑州运维1期就业班,毕业14个工作日,班级93%同学已拿到Offer, 一线均薪资 1W+
2025-09-19【AI鸿蒙开发】上海校区AI鸿蒙开发4期5期,距离毕业21天,就业率91%,平均薪资14046元
2025-09-19