zoukankan      html  css  js  c++  java
  • python json序列化和反序列化

    json序列化

    python数据类型 -> json对象

    #!/usr/bin/env python3
    # -*- coding:utf-8 -*-
    import json
    
    
    # python字典对象
    contant = {
        'name': 'tester',
        'sex':'',
        'age': 18,
        'is_bool': True
    }
    
    
    def serialization(*args, **kwargs):
        """
        序列化
        """
        return json.dumps(*args, **kwargs)
    
    
    if __name__ == "__main__":
        print(serialization(contant))

    执行结果:

    {"name": "tester", "sex": "u7537", "age": 18, "is_bool": true}
    可以看到成功,序列化里面有以下特点:
    • 单引号被转换成了双引号
    • 可以正常转换数字
    • 中文被转码成Unicode
    • bool值True转换为ture

    我们能让中文正常显示吗?当然可以,只需要在序列化时设置一个参数。

    if __name__ == "__main__":
        print(serialization(contant,ensure_ascii=False))

    运行结果:

    {"name": "tester", "sex": "", "age": 18, "is_bool": true}
    可以看到中文已经正常显示了。

    json反序列化

    json对象 -> python数据类型

    #!/usr/bin/env python3
    # -*- coding:utf-8 -*-
    import json
    
    
    contant = {
        'name': 'tester',
        'sex': '',
        'age': 18,
        'is_bool': True
    }
    
    
    def serialization(*args, **kwargs):
        """
        序列化
        """
        return json.dumps(*args, **kwargs)
    
    
    def deserialization(*args, **kwargs):
        """
        反序列化
        """
        return json.loads(*args, **kwargs)
    
    
    if __name__ == "__main__":
        res = serialization(contant, ensure_ascii=False)
        print(deserialization(res))

    执行结果:

    {'name': 'tester', 'sex': '', 'age': 18, 'is_bool': True}
    可以看到反序列化之后结果都显示回了contant变量定义的python字典对象

    那我们能不能直接反序列化contant字典呢?我们来试一下

    if __name__ == "__main__":
        print(deserialization(contant))

    运行结果:

      File "D:Python3libjson\__init__.py", line 341, in loads
        raise TypeError(f'the JSON object must be str, bytes or bytearray, '
    TypeError: the JSON object must be str, bytes or bytearray, not dict

    可以看到报错了,大致意思为:json对象应该时一个字符串,字节或字节数组;不是一个字典。

    所以我们在反序列化的时候传的值必须时json对象格式。

    类型对照表

    PythonJSON
    dict object
    list, tuple array
    str, unicode string
    int, long, float number
    True true
    False false
    None null

    判断字符串是不是json格式

    import json
    from json import JSONDecodeError
    
    def is_json_str(string):
        """判断是否是json格式字符串"""
        if isinstance(string, str):
            try:
                json.loads(string)
                return True
            except JSONDecodeError:
                return False
        return False
  • 相关阅读:
    zoj 2316 Matrix Multiplication 解题报告
    BestCoder7 1001 Little Pony and Permutation(hdu 4985) 解题报告
    codeforces 463C. Gargari and Bishops 解题报告
    codeforces 463B Caisa and Pylons 解题报告
    codeforces 463A Caisa and Sugar 解题报告
    CSS3新的字体尺寸单位rem
    CSS中文字体对照表
    引用外部CSS的link和import方式的分析与比较
    CSS样式表引用方式
    10个CSS简写/优化技巧
  • 原文地址:https://www.cnblogs.com/wxhou/p/json.html
Copyright © 2011-2022 走看看