Example analysis of Python3.x operations on JSON

巴扎黑
Release: 2017-09-02 12:01:26
Original
1618 people have browsed it

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)
Copy after login

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"]}
Copy after login

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)
Copy after login

Output:


[{"id": "2203", "title": "title", "subTitle": "sub title"}, {"id": "2842", "title": "b标题", "subTitle": "b副标题", "content": "内容"}]
Copy after login
This JSON string can be converted to the corresponding object using the plug-in GsonFormat in Android Studio.

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!

Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template