python3之json模块使用

1. json模块介绍

json是python自带的操作json的模块。

python序列化为json时的数据类型转换关系:

python格式 json格式
dict(复合类型) object
list, tuple(集合类型) array
int, long, float(数值类型) number
str, unicode string
True true
False false
None null

json反序列化为python数据类型对照关系:

json格式 python格式
object dict
array list
string unicode
number(int) int, long
numer(real) float
true True
false False
null None

2. 如何使用

json库提供了几个API:

json.dumps(): 将字典序列化为json字符串

json.loads(): 将json字符串反序列化为字典

json.dump(): 将字典序列化到一个文件,是文本文件,就是相当于将序列化后的json字符串写入到一个文件

json.load(): 从文件中反序列出字典

总结: 不带s的是序列到文件或者从文件中反序列化,带s的是都在内存中操作不涉及到持久化

一个简单使用的例子如下:

#! /usr/bin/python

import json


if __name__ == '__main__':
    cc = {
        "name": "CC11001100",
        "age": 22,
        "money": 9.9,
        "car": "Feng-Huang Bicycle",
        "house": "祖宅",
        "girl friend": None,
        "hobby": "thinking..."
    }

    # 序列化为字符串
    json_string = json.dumps(cc)
    print(json_string)
    # 从字符串中反序列化
    json_dict = json.loads(json_string)
    print(json_dict)

    # 序列化到文件中
    with open('D:/cc.json', 'w') as json_file:
        json.dump(cc, json_file)
    # 从文件中反序列化
    with open('D:/cc.json', 'r') as json_file:
        json_dict = json.load(json_file)
        print(json_dict)

py对象序列化为json的时候会接受的几个参数:

indent: 即缩进量是几个空格,当需要格式化输出的时候一般设为4个空格

一个指定indent的小例子:

#! /usr/bin/python

import json

if __name__ == '__main__':
    cc = {
        "name": "CC11001100",
        "age": 22,
        "money": 9.9,
        "car": "Feng-Huang Bicycle",
        "house": "祖宅",
        "girl friend": None,
        "hobby": "thinking..."
    }
    print(json.dumps(cc, indent=4))

输出:

{
    "name": "CC11001100",
    "age": 22,
    "money": 9.9,
    "car": "Feng-Huang Bicycle",
    "house": "u7956u5b85",
    "girl friend": null,
    "hobby": "thinking..."
}

separators: 生成的json子串所使用的分隔符,就是用来代替分隔多个k/v对的,和分隔k/v的:

一个指定了separators的小例子:

#! /usr/bin/python

import json

if __name__ == '__main__':
    cc = {
        "name": "CC11001100",
        "age": 22,
        "money": 9.9,
        "car": "Feng-Huang Bicycle",
        "house": "祖宅",
        "girl friend": None,
        "hobby": "thinking..."
    }
    print(json.dumps(cc, indent=4, separators=('↓', '→')))

输出:

{
    "name"→"CC11001100"↓
    "age"→22↓
    "money"→9.9↓
    "car"→"Feng-Huang Bicycle"↓
    "house"→"u7956u5b85"↓
    "girl friend"→null↓
    "hobby"→"thinking..."
}

sort_keys:是否对key进行排序,目前还没感觉出有啥用

3. 自带json模块的局限性

使用自带的json模块虽然很方便,但是序列化自定义类型的时候就会抛出一个TypeError的异常:

TypeError: Object of type 'Person' is not JSON serializable

对于自定义类型的序列化,一般都是使用第三方库,当然这个是另外的内容了。

参考资料:

1. https://docs.python.org/2/library/json.html

原文地址:https://www.cnblogs.com/cc11001100/p/7630429.html