使用jsonpath提取json数据指定参数的值,json文件如下所示
{
"name": "atool",
"url": "https://atool.vip/",
"author": [
{
"id": "hustcc",
"age": 24,
"developer": true
},
{
"id": "wzq",
"age": 24,
"developer": true
}
],
"tags": [
"在线工具",
"online",
"free",
"javascript"
],
"describe": "网站前身为 atool.org,重构 ui 而来!"
}
代码如下所示
#!usr/bin/env python
#-*- coding:utf-8 -*-
"""
@author:doulihang
@file: json_path_test.py
@time: 2019/05/08
"""
import json
import jsonpath
with open("data.json", 'r') as load_f:
# 将已编码的 JSON 字符串解码为Python对象
load_dict = json.load(load_f)
"""使用jsonpath进行匹配"""
#获取根节点下所有name的值
a = jsonpath.jsonpath(load_dict,expr="$.name")
print(a)
#获取author下第一个字典id的值
b = jsonpath.jsonpath(load_dict,expr="$.author[0].id")
print(b)
#获取最后一个tags值
c = jsonpath.jsonpath(load_dict,expr="$.tags[-1:]")
print(c)
#获取前三个tags值
d = jsonpath.jsonpath(load_dict,expr="$.tags[0:3]")
print(d)
#获取第二个、第四个tags值
e = jsonpath.jsonpath(load_dict,expr="$.tags[1,3]")
print(e)