json to str json.dumps 会保证输出是合法的 json 字符串
param = {"cmdType" : 90001 , "param" : {"table" : "t_user" , "column" : ["f_id" , "f_ui_id" , "f_group_id" ], "where" : ["f_name" , "f_pwd" ],"value" : ["admin" , "4acb4bc224acbbe3c2bfdcaa39a4324e" ]}} resp = rpc_client(json.dumps(param))
str to json final_dictionary = json.loads(resp) # resp is str type final_dictionary = eval(resp) eval(json_str, {'false': False, 'true': True, 'null': None}) eval(str, {'__builtins__':{ }})
json.loads 将 json 中的字符串转成 unicode(types.UnicodeType),eval 转成了 str(types.StringType) 读取中文的时候 json.loads 会报错 。(奇怪现在发现没报错 2021.04.12)
json to file import jsondata = {} data['people' ] = [] data['people' ].append({ 'name' : 'Scott' , 'website' : 'stackabuse.com' , 'from' : 'Nebraska' }) data['people' ].append({ 'name' : 'Larry' , 'website' : 'google.com' , 'from' : 'Michigan' }) data['people' ].append({ 'name' : 'Tim' , 'website' : 'apple.com' , 'from' : 'Alabama' }) with open ('data.txt' , 'w' ) as outfile: json.dump(data, outfile)
file to json import jsonwith open ('data.txt' ) as json_file: data = json.load(json_file) for p in data['people' ]: print ('Name: ' + p['name' ]) print ('Website: ' + p['website' ]) print ('From: ' + p['from' ]) print ('' )