一、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": "内容"}]

三、参考文章

https://blog.csdn.net/qq_35622837/article/details/82771508

Logo

开放原子开发者工作坊旨在鼓励更多人参与开源活动,与志同道合的开发者们相互交流开发经验、分享开发心得、获取前沿技术趋势。工作坊有多种形式的开发者活动,如meetup、训练营等,主打技术交流,干货满满,真诚地邀请各位开发者共同参与!

更多推荐