zoukankan      html  css  js  c++  java
  • 14.json文件读取

    json文件读取
    1.#读取json
    
    import json
    
    str='''[
        {
        "name":"Tom",
        "gender":"male",
        "birth":"1997-12-13"
        },
        {
        "name": "Jerry",
        "gender": "male",
        "birth": "1998-10-18"
        }
    ]'''
    
    #注意问题  json字符串的表示需要用双引号,否则loads()方法会解析失败
    
    
    print(type(str))
    data=json.loads(str)
    print(data)
    print(type(data))
    
    
    print(data[0]['birth'])

    执行结果如图:

    2.#读取json
    
    import json
    
    data=[
        {
        'name':'Tom',
        'gender':'male',
        'birth':'1997-12-13'
        },
        {
        'name': 'Jerry',
        'gender': 'male',
        'birth': '1998-10-18'
        }
    ]
    
    # 将json对象转为字符串,然后调用文件的write()方法写入文本
    with open('data.json','w')as file:
        file.write(json.dumps(data))

    运行结果如图:

    3.#读取json
    
    import json
    
    data=[
        {
        'name':'德玛西亚',
        'gender':'male',
        'birth':'1997-12-13'
        },
        {
        'name': 'Jerry',
        'gender': 'male',
        'birth': '1998-10-18'
        }
    ]
    
    #保存json格式,添加一个参数indent,代表缩进字符个数。
    #为了输出中文 指定参数 ensure_ascii=False
    
    with open('data.json3','w')as file:
        file.write(json.dumps(data,indent=2))
        # file.write(json.dumps(data,indent=2,ensure_ascii=False))

    执行结果如图:

  • 相关阅读:
    android中的webview白屏问题
    7-24分享
    Excel----考勤表制作自动更新日期
    (二十五)微信小程序的登陆 实际逻辑
    微信退款流程
    (二十八)加锁
    (二十七)竞价
    (二十六)拍卖专场相关的接口
    (二十六)微信小程序支付流程
    (二十四)微信小程序支付
  • 原文地址:https://www.cnblogs.com/lvjing/p/9708779.html
Copyright © 2011-2022 走看看