字符串,列表转json

import json

# 涉及到中文字符的时候,需要指定ensure_ascii=False
# 字符串转json
strData = '{"name": "John", "age": 30, "city": "New York"}'
# 第一步将字符串解析为python对象
strLoads = json.loads(strData)
# 第二步将python对象转化为json字符串
strDumps = json.dumps(strLoads,ensure_ascii=False)
print("loads字符串转Json:", strLoads)
print("loads字符串转Json类型:", type(strLoads))
print("dumps字符串转Json:", strDumps)
print("dumps字符串转Json类型:", type(strDumps))
# 列表转json
listData = [{"name": "John", "age": 30, "city": "New York"}]
# 第二步将python对象转化为json字符串
listDumps = json.dumps(listData)
print("dumps列表转Json:", listDumps)
print("dumps列表转Json类型:", type(listDumps))

结果:

loads字符串转Json: {'name': 'John', 'age': 30, 'city': 'New York'}
loads字符串转Json类型: <class 'dict'>
dumps字符串转Json: {"name": "John", "age": 30, "city": "New York"}
dumps字符串转Json类型: <class 'str'>
dumps列表转Json: [{"name": "John", "age": 30, "city": "New York"}]
dumps列表转Json类型: <class 'str'>

posted @ 2023-10-09 10:29  公子Learningcarer  阅读(48)  评论(0编辑  收藏  举报