zoukankan      html  css  js  c++  java
  • 第5.1章 json文件操作

    json数据示例

    {
        "single": {
            "is_guest_record": 0,
            "kms": [],
            "path": [{
                "time": 1509708120,
            }],
            "pc_type": "OPPO R9s"
        }
    }

    python与json文件数据类型对比

     
    python json
    dict {}
    list,tuple []
    str string
    int,float number
    True/False true/false
    None null

    示例

    import json
    
    python_dict = {'id':10,'name':'li4','likes':['看书','游戏'],'study':{'AI':('python','Ruby'),'大数据':('kafka',)},'if_vip':True}
    
    # python数据转换为json类型字符串
    json_str = json.dumps(python_dict,ensure_ascii=False)
    print(json_str)
    print(type(json_str))
    
    # json字符串转换为python数据
    python_data = json.loads(json_str)
    print(python_data)
    print(type(python_data))
    
    # python数据转换为json类型字符串,并写入json文件
    with open('file/jsonfile.json','w',encoding='utf-8') as f:
        json.dump(python_dict,f,ensure_ascii=False)
    
    # 读取json文件,并将json字符串转换为python数据
    with open('file/jsonfile.json','r',encoding='utf-8') as f:
        python_data1 = json.load(f)
        print(python_data1)
  • 相关阅读:
    python基础12-语法
    基础篇-内置函数(常用)
    中级篇-内置函数 (map/filter/reduce)
    python 基础11-递归
    python 基础10-函数、变量
    python 基础9-拼接
    redis
    python--os模块
    函数return多个值
    python--文件读写
  • 原文地址:https://www.cnblogs.com/bxbyy/p/8994804.html
Copyright © 2011-2022 走看看