zoukankan      html  css  js  c++  java
  • Python学习---JSON补充内容[中文编码 + dumps解析]

    JSON补充内容[微信解决中文乱码,接上]

    import json
    
    # 英文显示
    dic = {"hello": "world"}
    str = json.dumps(dic)
    # type(str) <class 'str'> str: {"hello": "world"}
    print("type(str)", type(str), 'str:', str)
    
    # 中文显示
    r = {"key": "中国"}
    st = json.dumps(r)  # 序列化后变成字符串,中文变成ascii编码
    # type(st) <class 'str'> st: {"key": "u4e2du56fd"}
    print("type(st)", type(st), 'st:', st)
    
    # 中文bytes处理
    b = bytes(st, encoding="utf-8")
    # type(b): <class 'bytes'> b: b'{"key": "\u4e2d\u56fd"}'  # 发送utf-8字节给微信服务器
    print("type(b):",type(b), "b:", b)
    
    # 解决方案一: 不使用ensure_ascill编码
    k = {"key": "中国"}
    new = json.dumps(k, ensure_ascii=False)
    print(new)   # {"key": "中国"}
    bb = bytes(new, encoding="utf-8")
    print(bb)  # b'{"key": "xe4xb8xadxe5x9bxbd"}'
    
    # 解决方案二:先对字典中的msg信息进行占位符处理,然后进行json.dumps[此时是字符串了],接着利用占位符传入msg信息
    l = {"key": '%(msg)s' }  # 注意引号
    new1 = json.dumps(l)
    print(new1)  # {"key": "%(msg)s"}
    new1 = new1 %{'msg': '中国'}
    print(new1)  # {"key": "中国"}
    pp = bytes(new, encoding="utf-8")
    print(pp)  # b'{"key": "xe4xb8xadxe5x9bxbd"}'
    '''
    总述:
        问题定位:
            json.dumps()将中文进行了Ascii编码[默认编码]后返回编码后的字符串【u4e2du56fd】
            bytes()将字符串转变为字节进行发送【\u4e2d\u56fd】
               微信接到消息后进行字节byte向字符串str转换,然后发送给前台。即【\u4e2d\u56fd】 --》【u4e2du56fd】 --》乱码
        问题解决:
            1. 不使用ASCII编码,则直接返回中文后进行字节编码  json.dumps(k, ensure_ascii=False)
            2. 使用占位符,在json.dumps()后传入msg信息进去  j = j %{"msg": msg} -->此时显示中文
    '''

    image_thumb[1]

    Json.dumps(cls参数内容以及转换规则)

    if cls is None:
        cls = JSONEncoder
    
    +-------------------+---------------+
    | Python            | JSON          |
    +===================+===============+
    | dict              | object        |
    +-------------------+---------------+
    | list, tuple       | array         |
    +-------------------+---------------+
    | str               | string        |
    +-------------------+---------------+
    | int, float        | number        |
    +-------------------+---------------+
    | True              | true          |
    +-------------------+---------------+
    | False             | false         |
    +-------------------+---------------+
    | None              | null          |
    +-------------------+---------------+
  • 相关阅读:
    导出报ora-31634、ora-31664
    A significant part of sql server process memory has been paged out
    解决ora-02429:无法用于删除强制唯一/主键的索引
    更改数据库表中有数据的字段类型NUMERIC(18,2)为NUMERIC(18,6)
    GHOST CLEANUP Process
    oracle查看执行计划explain plan FOR
    ORA-01502: 索引或这类索引的分区处于不可用状态
    mysql 游标循环,嵌套游标循环
    MSSQL FOR XML PATH ('')用法
    Mysql CHARINDEX用法
  • 原文地址:https://www.cnblogs.com/ftl1012/p/9425428.html
Copyright © 2011-2022 走看看