zoukankan      html  css  js  c++  java
  • json数据处理:读取文件中的json字符串,转为python字典

    方法1:

    读取文件中的json字符串,

    再用json.loads转为python字典

    import json
    
    str_file = './960x540/config.json'
    with open(str_file, 'r') as f:
        print("Load str file from {}".format(str_file))
        str1 = f.read()
        r = json.loads(str1)
    print(type(r))
    print(r)
    print(r['under_game_score_y'])
    

      

    方法2:

    直接用文件游标f,将json字符串连同读取和转成python字典一步完成。此时用的是josn.load(f)

    import json
    
    str_file = './960x540/config.json'
    with open(str_file, 'r') as f:
        print("Load str file from {}".format(str_file))
        r = json.load(f)
    print(type(r))
    print(r)
    print(r['under_game_score_y'])
    

      

    结论:

    json模块中的loads和load的区别是:

    loads是将f游标中的字符串先读取出来,在把字符串转成python字典

    load是一步到位把文件游标f转成python字典。

    延伸:

    json字符串转成字典{}

    dict_data=json.loads(json_data)
    

      

    字典{}转成json字符串

    json_data=json.dumps(dict_data, ensure_ascii=False)
    

      

    ensure_ascii=False表示输出汉字。

  • 相关阅读:
    CF 319C
    日常---区域赛临近
    poj 3728 The merchant 倍增lca求dp
    zoj 3742 Delivery 好题
    zoj 3717 Balloon 2-sat
    CF 163E. e-Government ac自动机+fail树+树状数组
    CF 335B
    hdu 4739 状压DP
    hdu 4738 桥
    Hibernate中的继承映射
  • 原文地址:https://www.cnblogs.com/andy9468/p/8252897.html
Copyright © 2011-2022 走看看