【将字典转换成字符串,将字符串转换为字典】

将字符串转换为字典

#方法1
import json
str_representation = '{"name": "John", "age": 30, "city": "New York"}'
my_dict = json.loads(str_representation)
print(my_dict)

#方法2
str_representation = '{"name": "John", "age": 30, "city": "New York"}'
my_dict = eval(str_representation)
print(my_dict)

将字典转换成字符串

#方法1
import json
my_dict = {'name': 'John', 'age': 30, 'city': 'New York'}
str_representation = json.dumps(my_dict)
print(str_representation)

#方法2
my_dict = {'name': 'John', 'age': 30, 'city': 'New York'}
str_representation = str(my_dict)
print(str_representation)

你可能感兴趣的:(python)