发布时间:2019-09-22 08:09:12编辑:auto阅读(3670)
一、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'} {"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": "内容"}]
这一个JSON字符串可以在Android Studio中利用插件GsonFormat转换得到相应对象。
上一篇: python 判断网络连通
下一篇: 用Python实现一个简单的WebSoc
47827
46355
37249
34709
29297
25956
24868
19930
19508
17996
5774°
6397°
5908°
5952°
7052°
5896°
5926°
6420°
6386°
7754°