Python中字典与字符串类型相互转换

import json

def str_to_dict():
    res = json.loads('{"name": "xiaoming", "age": 18}')
    print("对象类型:", type(res))
    print("姓名:{}, 年龄:{}".format(res['name'], res['age']))

def dict_to_str():
    dictObj = {"name": "xiaofang", "age": 25}
    dictStr = json.dumps(dictObj)
    print("对象类型:", type(dictStr))
    print(dictStr)

if __name__ == '__main__':
    str_to_dict()
    dict_to_str()

输出结果:

对象类型: 
姓名:xiaoming, 年龄:18
对象类型: 
{"name": "xiaofang", "age": 25}

你可能感兴趣的:(Python,python,开发语言,后端)