一、Dictionary 转为JSON
将dict转为JSON,这里利用包json
import json
aItem = {}
aItem["id"] = "2203"
aItem["title"] = "title"
aItem["subTitle"] = "sub title"
bItem = {}
bItem["id"] = "2842"
bItem["title"] = "b标题"
bItem["subTitle"] = "b副标题"
bItem["content"] = "内容"
bItem["list"] = ["a", "a 2", "b", "bb"]
aJson = json.dumps(aItem)
bJson = json.dumps(bItem, ensure_ascii=False)
print(aItem)
print(aJson)
print(bJson)
涉及到中文字符时,需要指定ensure_ascii=False,输出:
# 字典元素使用单引号
{'id': '2203', 'title': 'title', 'subTitle': 'sub title'}
# JSON元素使用双引号
{"id": "2203", "title": "title", "subTitle": "sub title"}
{"id": "2842", "title": "b标题", "subTitle": "b副标题", "content": "内容", "list": ["a", "a 2", "b", "bb"]}
二、list转JSON
接上面的代码
jsonList = []
jsonList.append(aItem)
jsonList.append(bItem)
jsonArr = json.dumps(jsonList, ensure_ascii=False)
print(jsonArr)
输出:
[{"id": "2203", "title": "title", "subTitle": "sub title"}, {"id": "2842", "title": "b标题", "subTitle": "b副标题", "content": "内容"}]