python-json

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

// 推荐使用 json 函数载入, eval 不够安全
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 json

data = {}
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 json

with 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('')