Home > Backend Development > Python Tutorial > In-depth understanding of python's operation summary of json

In-depth understanding of python's operation summary of json

高洛峰
Release: 2017-02-23 16:30:54
Original
1509 people have browsed it

The most widely used application of Json is as a data format for communication between web servers and clients in AJAX. This article mainly introduces a summary of python's operation of json, which has certain reference value. Those who are interested can learn more.

Json introduction: Json, full name JavaScript Object Notation, is a lightweight data exchange format. The most widely used application of Json is as a data format for communication between web servers and clients in AJAX. Nowadays, it is also commonly used in http requests, so it is natural to learn all kinds of json. Python’s official website address: https://docs.python.org/2/library/json.html?highlight=json#module-json

Json API usage: Python needs to be downloaded before version 2.6 The package can only be used after installation, which is somewhat similar to using SeleniumLibrary in RF today. But in 2.6, the official documentation (https://docs.python.org/2.6/whatsnew/2.6.html) clearly states that "there are some important new packages added to the standard library, such as multiprocessing and json, but with Compared with python 3 and 2.6, these packages will not introduce more new features. "So when installing children's shoes of python 2.6 or above, you don't need to download the json package. You can directly import json where you need it and use it after installation. Under Lib in the directory, you can see these two packages (click in and read the source codes carefully, you will get more results,) as shown below: Versions 6 and above support Json encoding and decoding, and support conversion of most of Python's built-in types with Json. The simplest example is as follows:

In-depth understanding of pythons operation summary of json

>>> import json
>>> data = {"spam" : "foo", "parrot" : 42}
>>> in_json = json.dumps(data) # Encode the data
>>> in_json
'{"parrot": 42, "spam": "foo"}'
>>> json.loads(in_json) # Decode into a Python object
{"spam" : "foo", "parrot" : 42}
Copy after login

The Encode process is a process of converting python objects into json objects. The two commonly used functions are dumps and dump function. The only difference between the two functions is that dump converts the python object into a json object to generate an fp file stream, while dumps generates a string:

In-depth understanding of pythons operation summary of jsonThe use of other parameters is the same. The following are some code snippets for learning:

In-depth understanding of pythons operation summary of json

dic1 = {'type':'dic1','username':'loleina','age':16}
json_dic1 = json.dumps(dic1)
print json_dic1
json_dic2 = json.dumps(dic1,sort_keys=True,indent =4,separators=(',', ': '),encoding="gbk",ensure_ascii=True )
print json_dic2
Copy after login

The running results are as follows:

If If the value of key 'username' in the example is replaced by the Chinese word "test", an error will be reported if the first conversion without parameters is used, but the second conversion with parameters will run normally.

In-depth understanding of pythons operation summary of json

is actually a process of understanding the parameters of the function. Here are several commonly used parameters:

Skipkeys: The default value is False, if The data in the keys of dict is not the basic type of Python (str, unicode, int, long, float, bool, None). When set to False, a TypeError will be reported. If set to True at this time, this type of key will be skippedIn-depth understanding of pythons operation summary of json

ensure_ascii: The default value is True. If the dict contains non-ASCII characters, the data will be displayed similar to \uXXXX. After setting it to False, it will Can be displayed normally

indent: should be a non-negative integer. If it is 0 or empty, the data will be displayed in one line. Otherwise, it will wrap to another line and display the preceding blank according to the number of indents. This is how it is printed. Json data is also called pretty-printed json

separators: The separator is actually a tuple of (item_separator, dict_separator). The default is (',',':'); this means the keys in the dictionary They are separated by ",", and KEY and value are separated by ":".

encoding: The default is UTF-8, set the encoding method of json data.

sort_keys: Sort data according to the values ​​of keys.

The Decode process is a process of converting json objects into python objects. The two commonly used functions are loads and load functions. The difference is the same as dumps and dumps.

if __name__ == '__main__':
  # 将python对象test转换json对象
  test = [{"username":"测试","age":16},(2,3),1]
  print type(test)
  python_to_json = json.dumps(test,ensure_ascii=False)
  print python_to_json
  print type(python_to_json)

  # 将json对象转换成python对象
  json_to_python = json.loads(python_to_json)
  print json_to_python
  print type(json_to_python)
Copy after login

The running results are as follows:

从上面2个例子的测试结果可以看到,python的一些基本类型通过encode之后,tuple类型就转成了list类型了,再将其转回为python对象时,list类型也并没有转回成tuple类型,而且编码格式也发生了变化,变成了Unicode编码。具体转化时,类型变化规则如下所示:

Python-->Json

In-depth understanding of pythons operation summary of json

Json-->Python

In-depth understanding of pythons operation summary of json

Json处理中文问题:

关于python字符串的处理问题,如果深入的研究下去,我觉得可以写2篇文章了(实际上自己还没整很明白),在这里主要还是总结下使用python2.7.11处理json数据的问题。前期做接口测试,处理最多的事情就是,把数据组装成各种协议的报文,然后发送出去。然后对返回的报文进行解析,后面就遇到将数据封装在json内嵌入在http的body内发送到web服务器,然后服务器处理完后,返回json数据结果的问题。在这里面就需要考虑json里有中文数据,怎么进行组装和怎么进行解析,以下是基础学习的一点总结:

第一:Python 2.7.11的默认编码格式是ascii编码,而python3的已经是unicode,在学习编解码的时,有出现乱码的问题,也有出现list或者dictionary或者tuple类型内的中文显示为unicode的问题。出现乱码的时候,应该先看下当前字符编码格式是什么,再看下当前文件编码格式是什么,或者没有设置文件格式时,查看下IDE的默认编码格式是什么。最推崇的方式当然是每次编码,都对文件编码格式进行指定,如在文件前 设置# coding= utf-8。

第二:字符串在Python内部的表示是unicode编码,因此,在做编码转换时,通常需要以unicode作为中间编码,即先将其他编码的字符串解码(decode)成unicode,再从unicode编码(encode)成另一种编码。decode的作用是将其他编码的字符串转换成unicode编码,如str1.decode('gb2312'),表示将gb2312编码的字符串str1转换成unicode编码。encode的作用是将unicode编码转换成其他编码的字符串,如str2.encode('gb2312'),表示将unicode编码的字符串str2转换成gb2312编码。因此,转码的时候一定要先搞明白,字符串str是什么编码,然后decode成unicode,然后再encode成其他编码

第三:将json数据转换成python数据后,一般会得到一个dict类型的变量,此时内部的数据都是unicode编码,所以中文的显示看着很痛苦,但是对于dict得到每个key的value后,中文就能正常显示了,如下所示:

# coding= utf-8
import json
import sys

if __name__ == '__main__':
  # 将python对象test转换json对象
  test = {"username":"测试","age":16}
  print type(test)
  python_to_json = json.dumps(test,ensure_ascii=False)
  print python_to_json
  print type(python_to_json)

  # 将json对象转换成python对象
  json_to_python = json.loads(python_to_json)
  print type(json_to_python)
  print json_to_python['username']
Copy after login

运行结果:

In-depth understanding of pythons operation summary of json

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持PHP中文网。

更多In-depth understanding of pythons operation summary of json相关文章请关注PHP中文网!


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