Recently in learning Python3, happened to encounter some JSON operation, simply tidy up to share out, the following this article mainly to you about python3.x some of the operation of the JSON, the need for friends can reference, the following with small series to learn together.
Objective
This article mainly introduce to you about Python3 to json some operation, share out for everyone reference study, the following words do not say more, come together to see the detailed introduction bar.
First, Dictionary to JSON
Convert Dict to JSON, using package JSON
Import Jsonaitem = {}aitem["id"] = "2203" aitem["title"] = "title" aitem["SubTitle"] = "Sub title" Bitem = {}bitem["id"] = "2 842 "bitem[" title "] =" b title "bitem[" SubTitle "] =" b subtitle "bitem[" Content "=" contents "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 specifyensure_ascii=False
Output:
{' id ': ' 2203 ', ' title ': ' title ', ' SubTitle ': ' Sub title '} {"id": "2203", "title": "title", "SubTitle": "Sub title"} {"id": "2842", "title": "B title", "SubTitle": "B subtitle", "Content": "Contents", "List": ["a", "a 2", "B", "BB"]}
Second, list is converted to JSON
Connect the code above
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 to a corresponding object in Android studio using the plugin Gsonformat.