Python 3.x and Python 3.xjson
Preface
This article mainly introduces some operations of python3 on JSON and shares them for your reference. I will not talk about them here. Let's take a look at the details.
1. Convert Dictionary to JSON
Convert dict to JSON. The json package is used here.
Import jsonaItem = {} aItem ["id"] = "2203" aItem ["title"] = "title" aItem ["subTitle"] = "sub title" bItem = {} bItem ["id"] = "2842" bItem ["title"] = "B title" bItem ["subTitle"] = "B subTitle" bItem ["content"] =" content "bItem [" list "] = [" ", "a 2", "B", "bb"] aJson = json. dumps (aItem) bJson = json. dumps (bItem, ensure_ascii = False) print (aItem) print (aJson) print (bJson)
When it involves Chinese characters, you must specifyensure_ascii=False
Output:
{'Id': '000000', 'title': 'title', 'title': 'sub title'} {"id": "2203", "title ": "title", "subTitle": "sub title"} {"id": "2842", "title": "B title", "subTitle": "B subTitle ", "content": "content", "list": ["a", "a 2", "B", "bb"]}
Ii. Convert list to JSON
Code
jsonList = []jsonList.append(aItem)jsonList.append(bItem)jsonArr = json.dumps(jsonList, ensure_ascii=False)print(jsonArr)
Output:
[{"Id": "2203", "title": "title", "subTitle": "sub title" },{ "id": "2842 ", "title": "B title", "subTitle": "B subTitle", "content": "content"}]
This JSON string can be converted using the plug-in GsonFormat in Android Studio to obtain the corresponding object.
Summary
The above is all the content of this article. I hope the content of this article will help you in your study or work. If you have any questions, please leave a message, thank you for your support.