Python中的json模塊的dump和dumps、load和loads的功能

Python中的json模塊的dump和dumps、load和loads的功能

JSON

首先簡單介紹一下json格式文件。json是JavaScript Object Notation的縮寫。顧名思義,json來源於js的對象的格式。現在json已經不在侷限於某種語言,而是一種通用的,比xml更輕量級的數據交換形式。

json 的基本格式可以看做是嵌套的字典。通俗來講,就是再字典中的某個元素的值還是一個字典。我們都熟悉Python的字典dict類型,如果我們定義

json_dict = {'a':{'c':{'e':404}, 'f':233}, 'b':{'d':1}}

可以看到,'a’的取值是一個字典,這個字典包括’c’和’f’兩個key。其中,'c’的取值仍然是個字典,而f的取值則是一個數值。以此類推。。。這樣一個字典具有清晰的結構關係。因此可以用來傳輸一個具有結構化的數據體。

下面,我們看看json官網上的介紹:

JSON具有以下這些形式:

對象(object) 是一個無序的“‘名稱/值’對”集合。一個對象以“{”(左括號)開始,“}”(右括號)結束。每個“名稱”後跟一個“:”(冒號);“‘名稱/值’ 對”之間使用“,”(逗號)分隔。

數組(array) 是值(value)的有序集合。一個數組以“[”(左中括號)開始,“]”(右中括號)結束。值之間使用“,”(逗號)分隔。

在這裏插入圖片描述

值(value) 可以是雙引號括起來的字符串(string)、數值(number)、truefalsenull、對象(object)或者數組(array)。這些結構可以嵌套。

在這裏插入圖片描述

字符串(string) 是由雙引號包圍的任意數量Unicode字符的集合,使用反斜線轉義。一個字符(character)即一個單獨的字符串(character string)。

JSON的字符串(string)與C或者Java的字符串非常相似。

在這裏插入圖片描述

數值(number) 也與C或者Java的數值非常相似。只是JSON的數值沒有使用八進制與十六進制格式。

在這裏插入圖片描述

同時,可以在任意標記之間添加空白。

Python中的json模塊

Python的json模塊用於處理json格式的數據。主要有如下幾個函數:

  • json.dump()

  • json.dumps()

  • json.load()

  • json.loads()

dump是將python的dict數據體做成json形式,而load則相反,從文件或string中加載數據,並解析成dict的形式。

簡單來說,s可以理解爲string,帶有s的是將dict結構dump成str,或者從str中load一個dict,而沒有s的則將dict以json形式存到文件,或者從文件讀出json形式。

下面是官方文檔的usage:

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)

可以看出,dump主要的參數是obj和fp,分別代表dict和要保存的文件的handler,如果需要打印出來縮進好看的話,可以設置indent。另外,separator是一個二元組(item_sep, key_sep),也就是元素之間的分隔符,和key-value之間的分隔符,默認的是逗號和冒號,並且如果沒有indent,則逗號冒號後面都接一個空格,如果有indent,自然逗號後面就不需要空格了(因爲有縮進)。這個分隔符可以自行指定。還有一個比較有用的是sort_keys,如果指定爲True,則會按照key 進行排序。

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)

和上面一樣,只不過不是保存到file裏,而是轉成一個string。

Serialize obj to a JSON formatted str using this conversion table. The arguments have the same meaning as in dump(). Note Keys in key/value pairs of JSON are always of the type str. When a dictionary is converted into JSON, all the keys of the dictionary are coerced to strings. As a result of this, if a dictionary is converted into JSON and then back into a dictionary, the dictionary may not equal the original one. That is, loads(dumps(x)) != x if x has non-string keys.

json.load(fp, *, cls=None, object_hook=None, parse_float=None,
parse_int=None, parse_constant=None, object_pairs_hook=None, **kw)

load和loads同理。

Deserialize fp (a .read()-supporting text file or binary file containing a JSON document) to a Python object using this conversion table. object_hook is an optional function that will be called with the result of any object literal decoded (a dict). The return value of object_hook will be used instead of the dict. This feature can be used to implement custom decoders (e.g. JSON-RPC class hinting). object_pairs_hook is an optional function that will be called with the result of any object literal decoded with an ordered list of pairs. The return value of object_pairs_hook will be used instead of the dict. This feature can be used to implement custom decoders. If object_hook is also defined, the object_pairs_hook takes priority. Changed in version 3.1: Added support for object_pairs_hook. parse_float, if specified, will be called with the string of every JSON float to be decoded. By default, this is equivalent to float(num_str). This can be used to use another datatype or parser for JSON floats (e.g. decimal.Decimal). parse_int, if specified, will be called with the string of every JSON int to be decoded. By default, this is equivalent to int(num_str). This can be used to use another datatype or parser for JSON integers (e.g. float). parse_constant, if specified, will be called with one of the following strings: '-Infinity', 'Infinity', 'NaN'. This can be used to raise an exception if invalid JSON numbers are encountered. Changed in version 3.1: parse_constant doesn’t get called on ‘null’, ‘true’, ‘false’ anymore. To use a custom JSONDecoder subclass, specify it with the cls kwarg; otherwise JSONDecoder is used. Additional keyword arguments will be passed to the constructor of the class. If the data being deserialized is not a valid JSON document, a JSONDecodeError will be raised. Changed in version 3.6: All optional parameters are now keyword-only. Changed in version 3.6: fp can now be a binary file. The input encoding should be UTF-8, UTF-16 or UTF-32.

json.loads(s, *, encoding=None, cls=None, object_hook=None,
parse_float=None, parse_int=None, parse_constant=None,
object_pairs_hook=None, **kw)

Deserialize s (a str, bytes or bytearray instance containing a JSON document) to a Python object using this conversion table. The other arguments have the same meaning as in load(), except encoding which is ignored and deprecated. If the data being deserialized is not a valid JSON document, a JSONDecodeError will be raised. Changed in version 3.6: s can now be of type bytes or bytearray. The input encoding should be UTF-8, UTF-16 or UTF-32.

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章