zoukankan      html  css  js  c++  java
  • Python常用模块 -- json模块常用用法

    对Python数据类型进行序列化与反序列化

    dic = {'name': 'sun', 'age': 19, 'gender': 1}
    str_dic = json.dumps(dic)  # 序列化:将一个字典转换成一个字符串
    print(str_dic, type(str_dic))
    
    dic2 = json.loads(str_dic)  # 反序列化:将一个json字符串转换成一个字典
    print(dic2, type(dic2))
    
    # 还可以处理嵌套的数据类型
    list_dic = [1, ['a', 'b', 'c'], 3, {'k1': 'v1', 'k2': 'v2'}]
    str_dic = json.dumps(list_dic)
    print(str_dic, type(str_dic))
    list_dic2 = json.loads(str_dic)
    print(list_dic2, type(list_dic2))
    

    对文件句柄进行序列化与反序列化

    # 对文件句柄进行序列化与反序列化
    with open('json.txt', 'w') as f:
        json.dump(dic, f)
    
    with open('json.txt') as f:
        dic_content = json.load(f)
        print('dic_content', dic_content)
    
    # 注意。dump dumps 中文时,要将 ensure_ascii=False
    with open('json1.txt', 'w') as f:
        json.dump({'国家': '中国', 'other': 'nothing'}, f, ensure_ascii=False)
    
    with open('json2.txt', 'w') as f:
        json_content = json.dumps({'年龄': 18, '性别': '男'}, ensure_ascii=False)
        f.write(json_content)
    
  • 相关阅读:
    ajax是什么? ajax的交互模型? 同步和异步的区别? 如何解决跨域问题?
    集锦 比较好
    集锦
    伊甸园日历游戏
    晴天小猪历险记之Hill
    求无向图最小环算法
    旅行商简化版
    十字绣
    破坏石油运输系统问题
    强墙
  • 原文地址:https://www.cnblogs.com/sunch/p/12402634.html
Copyright © 2011-2022 走看看