I have been learning python3 recently and happened to encounter some json operations. I simply compiled them and shared them. The following article mainly introduces you to some operations on JSON in Python3.x. Friends who need it can refer to it. The following is Come and learn with me.
Preface
This article mainly introduces you to some operations on JSON in python3, and shares them for your reference and study. Not much to say below. Having said that, let’s take a look at the detailed introduction.
1. Convert Dictionary to JSON
Convert dict to JSON, here use the package 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)
When it comes to Chinese characters, you need to specify ensure_ascii=False
Output:
{'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"]}
2. Convert list to JSON
Continue the above code
##
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": "内容"}]
The above is the detailed content of Example analysis of Python3.x operations on JSON. For more information, please follow other related articles on the PHP Chinese website!