程序師世界是廣大編程愛好者互助、分享、學習的平台,程序師世界有你更精彩!
首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫知識
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式師世界 >> 編程語言 >  >> 更多編程語言 >> Python

Python operating JSON to realize network data exchange

編輯:Python

Catalog

Preface

JSON What is it? ?

JSON And XML Advantages and disadvantages of ?

take Python The object is encoded as JSON character string

take JSON The string is decoded to Python object

Solve the problem of Chinese garbled code

Preface

Science Python Middle control JSON Knowledge . After learning this article , You can learn the following :

1、JSON What is it? ?

2、JSON And XML Advantages and disadvantages of ?

3、 take Python The object is encoded as JSON character string

4、 take JSON The string is decoded to Python object

5、 solve JSON Chinese code scrambling

JSON What is it? ?

JSON The full name is JavaScript Object Notation, Is a lightweight data exchange format . first ,JSON It's just JavaScript Subset , But it quickly became popular because of its simplicity .

Most programming languages today support for JSON Analysis and generation of , And in recent years, a new force has emerged NoSQL The database also refers to JSON To design the data storage format , for example Mongodb Of BSON(Binary JSON).

JSON There are six data types :number、boolean、string、null、array、object. The first three are easy to understand , The fourth one null Corresponding Python Of None, The last two , Corresponding Python Lists and dictionaries .

{ "name": " Xiao Ming ", "age": 14, "gender": true, "grade": null, "skills": [ "JavaScript", "Java", "Python" ]}JSON And XML Advantages and disadvantages of ?

stay JSON Before appearance , People use XML Exchange data on the network , stay JSON When it appears , It basically replaced XML The location of . The similarities between the two are obvious , They are all structured languages , Can be used for network data exchange .

The biggest difference between the two lies in their “ Birth ” Different , That is, they are created for different purposes .

XML yes W3C( World wide web consortium ) Published extensible markup language (Extensible Markup Language), Originally designed to make up for HTML Deficiency , With strong scalability to meet the needs of network information release , With it “ At the same level ” There are :XHTML\CSS\ECMAScript etc. . It contains DTD、XSD、XPath、XSL And a lot of complicated specifications , In data storage 、 Extension and advanced retrieval are useful . Later it was used for network data exchange , It's a bit of overkill , Although competent , But it is also a little complicated and redundant .

and JSON yes ECMAScript A subset of the standard , It was designed to overcome XML Disadvantages in data exchange , So on the one hand , It looks like XML It also has a concise and clear hierarchy , On the other hand , It is better than XML Cabinet and delicate , It is more suitable for network data transmission .

JSON Nor is it without drawbacks , When there are many levels of structure , It will make people fall into the tedious and complex data node search , It is more readable than XML Bad .

take Python The object is encoded as JSON character string

take python Object to string , This process is also called serialization , In contrast , take JSON String to python object , This process is called deserialization .

The serialization format is as follows ,json.dumps() hold python Object serialization ,json.dump() Serialize... First , Then save the contents to a file :

json.dumps(obj,, skipkeys=False, ensure_ascii=True, check_circular=True, allow_nan=True, cls=None, indent=None, separators=None, default=None, sort_keys=False,*kw)json.dump(obj, fp,, skipkeys=False, ensure_ascii=True, check_circular=True, allow_nan=True, cls=None, indent=None, separators=None, default=None, sort_keys=False,*kw)In [1]: import jsonIn [2]: d = dict(name='Tom', age='8', score=88)In [3]: json.dumps(d)Out[3]: '{"name": "Tom", "age": "8", "score": 88}'In [4]: with open('test.json', 'w') as f: ...: json.dump(d, f)

The most commonly used parameters are :

ensure_ascii=True Set whether the code is ASCII, The default is , if False, The original code format is used

indent=None Set indent when printing , The default is not indent

separators=None Set separator , The value is (item_separator, dict_separator) Tuples , The default is (‘,’,’:’), This means keys In between “,” separate , and key and value In between “:” separate

sort_keys=False Set by key sorted , No sort by default

take JSON The string is decoded to Python object

The deserialization format is as follows ,json.loads() Read content from memory and parse ,json.load() Read content from file to parse :

json.loads(s,

, encoding=None, cls=None, object_hook=None, parse_float=None, parse_int=None, parse_constant=None, object_pairs_hook=None,

*kw)

json.load(fp,

, cls=None, object_hook=None, parse_float=None, parse_int=None, parse_constant=None, object_pairs_hook=None,

*kw)

In [1]: import json2In [2]: d = dict(name='Tom', age='8', score=88)In [3]: tom_json = json.dumps(d)In [4]: json.loads(tom_json)Out[4]: {'age': '8', 'name': 'Tom', 'score': 88}In [5]: with open('test.json', 'r') as f: ...: print(json.load(f)){'name': 'Tom', 'age': '8', 'score': 88}

json.loads() Than json.load() One more. encoding Parameters , You can recode the incoming string .

Solve the problem of Chinese garbled code

Serialized ensure_ascii Parameters and deserialized encoding Corresponding , Are dealing with character encoding , Once it's not handled well , It will lead to the problem of Chinese garbled code .

Python2 The character encoding of is at sixes and sevens , It has also been widely criticized , If you encounter Python2 project , Refer to the following examples to solve .

The string is in Python2 The internal expression is unicode code . therefore , When doing code conversion , Need to be unicode As an intermediate code , That is, decoding other encoded strings first (decode) become unicode, Again from unicode code (encode) Into another code .

# -*- coding: utf-8 -*- m = {'a' : ' Hello '} print m =>{'a': '\xe4\xbd\xa0\xe5\xa5\xbd'} print json.dumps(m) =>{"a": "\u4f60\u597d"}print json.dumps(m,ensure_ascii=False)=>{"a": " I'm sorry ソ"}print json.dumps(m,ensure_ascii=False).decode('utf8').encode('gb2312')=>{"a": " Hello "}

Python3 The default encoding format for is utf-8, The above example , It only needs ensure_ascii=False, It can be solved .

This is about Python operation JSON This is the end of the article on network data exchange , More about Python operation JSON Please search the previous articles of software development network or continue to browse the relevant articles below. I hope you will support software development network more in the future !



  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式師世界 All Rights Reserved