Python__模块(DATA-类型)__json / jsonpath

json(参数列表)

json.dumps

Python对象编码成JSON字符串

json.loads

已编码的JSON字符串解码为Python对象

json.dump

文件操作-python对象写入json文件

json.load

文件操作-json文件转换为python对象


json(参考代码)

类型转换

import json
''' 转json '''
test_data = [{"a": 1, "b": 2, "c": 3, "d": 4, "e": 5}]
rs = json.dumps(test_data)
print(rs)
''' 转对象 '''
jsonData = "{'a':1,'b':2,'c':3,'d':4,'e':5}"
text = json.loads(jsonData)
print(text)

类型转换(自定义)

import json, datetime
''' json自动转换类型输出 '''
class MyEncoder(json.JSONEncoder):
    def default(self, obj):
        if isinstance(obj, datetime.datetime):
            print("MyEncoder-datetime.datetime")
            return obj.strftime("%Y-%m-%d %H:%M:%S")
        if isinstance(obj, bytes):
            return str(obj, encoding="utf-8")
        if isinstance(obj, int):
            return int(obj)
        elif isinstance(obj, float):
            return float(obj)
        # elif isinstance(obj, array):
        #    return obj.tolist()
        else:
            return super(MyEncoder, self).default(obj)

""" 调用MyEncode """
# dict->json
"""
def dict_to_json(dict_obj,name, Mycls = None):
    js_obj = json.dumps(dict_obj, cls = Mycls, indent=4)
    with open(name, 'w') as file_obj:
        file_obj.write(js_obj)
dict_to_json(dict_obj={'test':123,'tt':'text'},name='./new_js.json',Mycls=MyEncoder)
"""
# json->dict
"""
def json_to_dict(filepath, Mycls = None):
    with open(filepath,'r') as js_obj:
        dict_obj = json.load(js_obj, cls = Mycls)
        return dict_obj
"""

文件操作

import json
""" 写入文件 """
json_str = {"a": 1, "b": 2, "c": 3}
with open("new.json", "w", encoding="utf-8") as file:
    json.dump(json_str, file, indent=4, ensure_ascii=False)
""" 读取文件 """
with open("new.json", "r", encoding="utf-8") as fw:
    injson = json.load(fw)
print(injson)
print(type(injson))

网页读取

from urllib.request import urlopen
import json
from pprint import pprint
u = urlopen(
    "https://s2-10623.kwimgs.com/udata/pkg/cloudcdn/img/lottie/share/share.json/"
)
resp = json.loads(u.read().decode("utf-8"))
pprint(resp)

jsonpath(简介)

json数据匹配方法

jsonpath是一种信息抽取类库,是从JSON文档中抽取指定信息的工具。

jsonpath采用xpath的基本概念。

jsonpath(安装)

pip install jsonpath


jsonpath(参数列表)

$

根节点

@

当前节点

.or[]

取子节点

..

递归下降

*

通配符,所有对象/元素,无论其名称

[]

迭代器表示(可以在里面做简单的迭代操作,如数组下表,根据内容选值等)

[,]

支持迭代器做多选

?()

应用过滤器(脚本)表达式

()

脚本表达式


jsonpath(参考代码)

综合例子

import jsonpath

box = {
    "data": {
        "list": [
            {
                "爬行": "小猫",
                "海洋": {"name": "海豚", "description": "智慧型"},
                "飞行": {"name": "雄鹰", "description": "敏锐型"},
            },
            {
                "爬行": "小狗",
                "海洋": {"name": "鲨鱼", "description": "刚猛型"},
                "飞行": {"name": "鸽子", "description": "传送型"},
                "number": 123,
            },
        ],
    },
    "test": {"name": "测试", "number": 999},
    "message": {"name": "信息"},
}

print("message:", box["message"])
print("message:", jsonpath.jsonpath(box, "$..message"))
print("list:", jsonpath.jsonpath(box, "$..list")[0])
print(jsonpath.jsonpath(box, "$..海洋.*"))                     # 海洋->所有的valve值
print(jsonpath.jsonpath(box, "$..海洋")[0])                    # 海洋->多个结果中的第一个
print(jsonpath.jsonpath(box, "$..海洋.description"))           # 海洋->description值
print(jsonpath.jsonpath(box, "$.data.list[*].爬行"))           # list->所有的爬行的值(精准化)
print(jsonpath.jsonpath(box, "$..爬行"))                       # data->所有的爬行的值(简化)
print(jsonpath.jsonpath(box, "$.data.list[*].爬行")[-1])       # data->list中倒数第一个爬行值
print(jsonpath.jsonpath(box, "$.data..飞行.description")[1])   # list->第二个飞行中的description值(精准化) 
print(jsonpath.jsonpath(box, "$..[?(@.number>800)]"))          # 匹配data->number>800的所有值
print(jsonpath.jsonpath(box, "$..[?(@.number>800)].number"))   # 匹配data->number>800的所有值,并取出number的值(条件化)

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

vip飞梦

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值