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表示输出汉字。

原文地址:https://www.cnblogs.com/andy9468/p/8252897.html