python json pickle

发布时间:2019-08-11 11:27:38编辑:auto阅读(1470)

    Python中用于序列化的两个模块

    • json     用于【字符串】和 【python基本数据类型】 间进行转换

    • pickle   用于【python特有的类型】 和 【python基本数据类型】间进行转换

    Json模块提供了四个功能:dumps、dump、loads、load

    pickle模块提供了四个功能:dumps、dump、loads、load

    import json
    s ='{"key":"value"}'
    dic = json.loads(s)
    str = json.dumps(dic)
    print(dic,type(dic))
    print(str,type(str))
    结果:
    {'key': 'value'} <class 'dict'>
    {"key": "value"} <class 'str'>

    如果你要处理的是文件而不是字符串,你可以使用 json.dump()json.load() 来编码和解码JSON数据。例如:

    # Writing JSON data
    with open('data.json', 'w') as f:
        json.dump(data, f)
    # Reading data back
    with open('data.json', 'r') as f:
        data = json.load(f)
    pickle   用于【python特有的类型】 和 【python基本数据类型】间进行转换

    wKioL1dWy6HR6HYuAABUpCNKHV0201.png-wh_50

    http://python3-cookbook.readthedocs.io/zh_CN/latest/c06/p02_read-write_json_data.html

关键字

上一篇: python中的shell操作

下一篇: Python 常见错误