Bootstrap

python中的JSONPath

文章目录


该库可以便捷的提取json中的值,

import json
from jsonpath import jsonpath

# 读入示例json数据
with open(r'.\33.64.250.45.json', encoding='utf-8') as j:
    demo_json = json.loads(j.read())


def function1():
    # $.. 根节点的stationLaneName代节点
    print(jsonpath(demo_json, '$..stationLaneName'))


def function2():
    # $..roadArea.*.points 根节点的roadCloseArea后代节点对应的所有points值
    # {"roadCloseArea":[{"prints":[]},{"prints":[]},{"prints":[]}]}
    # 此处的键值对:points->[],如果是points->“”,也是可以的
    print(jsonpath(demo_json,"$..roadCloseArea.*.points"))

    # 可以如下使用
    points = jsonpath(demo_json,"$..roadCloseArea.*.points")
    for i in points:
        print(i)


def function3():
    # $..roadCloseArea.*[name,num] 根节点roadCloseArea下的name和num值
    print(jsonpath(demo_json,"$..roadCloseArea.*[name,num]"))
    # 输出
    # ['出口02', 6, '出口04', 7, '出口06', 8, '出口08', 9, '出口10', 10, '出口12', 11, '出口14', 12, '出口16', 13, '出口18', 14]


def function4():
    # 选择roadCloseArea键的第0个子节点对应的name与num值
    print(jsonpath(demo_json, '$..roadCloseArea[0][name,num]'))

    # 选择roadCloseArea键的第1到3(不包括3)个子节点对应的name与num值
    print(jsonpath(demo_json, '$..roadCloseArea[1:3][name,num]'))

    # 配合@,选择roadCloseArea键的最后一个子节点对应的name与num值
    print(jsonpath(demo_json, '$..roadCloseArea[(@.length-1)][name,num]'))
    # 输出
    # ['出口02', 6]
    # ['出口04', 7, '出口06', 8]
    # ['出口18', 14]


if __name__ == '__main__':
    # function1()
    # function2()
    # function3()
    function4()
;