溫馨提示×

溫馨提示×

您好,登錄后才能下訂單哦!

密碼登錄×
登錄注冊×
其他方式登錄
點擊 登錄注冊 即表示同意《億速云用戶服務(wù)條款》

JSON在Python中的使用方法是什么

發(fā)布時間:2020-09-04 14:56:07 來源:億速云 閱讀:130 作者:小新 欄目:編程語言

這篇文章給大家分享的是有關(guān)JSON在Python中的使用方法是什么的內(nèi)容。小編覺得挺實用的,因此分享給大家做個參考。一起跟隨小編過來看看吧。

JSON介紹

JSON(JavaScript Object Notation) 是一種輕量級的數(shù)據(jù)交換格式。 易于人閱讀和編寫。同時也易于機器解析和生成。 它基于JavaScript Programming Language, Standard ECMA-262 3rd Edition - December 1999的一個子集。 JSON采用完全獨立于語言的文本格式,但是也使用了類似于C語言家族的習(xí)慣(包括C, C++, C#, Java, JavaScript, Perl, Python等)。 這些特性使JSON成為理想的數(shù)據(jù)交換語言。

JSON的兩種結(jié)構(gòu)
  1. “名稱/值”對的集合(A collection of name/value pairs)。不同的語言中,它被理解為對象(object),紀(jì)錄(record),結(jié)構(gòu)(struct),字典(dictionary),哈希表(hash table),有鍵列表(keyed list),或者關(guān)聯(lián)數(shù)組 (associative array)。

  2. 值的有序列表(An ordered list of values)。在大部分語言中,它被理解為數(shù)組(array)。

JSON在Python中的使用

在Python中操作JSON時需要引入json標(biāo)準(zhǔn)庫。

import json

類型轉(zhuǎn)換

Python類型轉(zhuǎn)JSON:

json.dump()

#1.Python的dict類型轉(zhuǎn)JSON
person_dict = {‘name’: ‘pig’, ‘a(chǎn)ge’: 18, ‘sex’: ‘man’, ‘hometown’: ‘江西撫州’}

indent參數(shù)為縮進空格數(shù)

person_dict_json = json.dumps(person_dict, indent=4)print(person_dict_json, ‘\n’)

2.Python的列表類型轉(zhuǎn)JSON

person_list = [‘pig’, 18, ‘man’, ‘江西撫州’]person_list_json = json.dumps(person_list)print(person_list_json, ‘\n’)

3、Python的對象類型轉(zhuǎn)JSON

person_obj = Person(‘pig’, 18, ‘man’, ‘江西撫州’)

中間的匿名函數(shù)是獲得對象所有屬性的字典形式

person_obj_json = json.dumps(person_obj, default=lambda obj: obj.dict, indent=4)print(person_obj_json, ‘\n’)

JSON轉(zhuǎn)Python類型:

json.loads()

4、JSON轉(zhuǎn)Python的dict類型

person_json = ‘{ “name”: “pig”,”age”: 18, “sex”: “man”, “hometown”: “江西撫州”}’
person_json_dict = json.loads(person_json)print(type(person_json_dict), ‘\n’)

5、JSON轉(zhuǎn)Python的列表類型

person_json2 = ‘[“pig”, 18, “man”, “江西撫州”]’
person_json_list = json.loads(person_json2)print(type(person_json_list), ‘\n’)

6、JSON轉(zhuǎn)Python的自定義對象類型

person_json = ‘{ “name”: “pig”,”age”: 18, “sex”: “man”, “hometown”: “江西撫州”}’

object_hook參數(shù)是將dict對象轉(zhuǎn)成自定義對象

person_json_obj = json.loads(person_json, object_hook=lambda d: Person(d[‘name’], d[‘a(chǎn)ge’], d[‘sex’], d[‘hometown’]))print(type(person_json_obj), ‘\n’)

Python和JSON數(shù)據(jù)類型對應(yīng)表

JSONPython
objectdict
arraylist
stringstr
numberint,long,float
true,falseTrue,F(xiàn)alse
nullNone

需要注意的點

JSON的鍵名和字符串都必須使用雙引號引起來,而Python中單引號也可以表示為字符串,所以這是個比較容易犯的錯誤!

Python類型與JSON相互轉(zhuǎn)換的時候到底是用load/dump還是用loads\dumps?

不加s的方法入?yún)⒍嗔艘粋€fp表示filepath,最后多了一個寫入文件的操作。

所以我們在記憶的時候可以這樣記憶:

加s表示轉(zhuǎn)成字符串(str),不加s表示轉(zhuǎn)成文件。

感謝各位的閱讀!關(guān)于JSON在Python中的使用方法是什么就分享到這里了,希望以上內(nèi)容可以對大家有一定的幫助,讓大家可以學(xué)到更多知識。如果覺得文章不錯,可以把它分享出去讓更多的人看到吧!

向AI問一下細(xì)節(jié)

免責(zé)聲明:本站發(fā)布的內(nèi)容(圖片、視頻和文字)以原創(chuàng)、轉(zhuǎn)載和分享為主,文章觀點不代表本網(wǎng)站立場,如果涉及侵權(quán)請聯(lián)系站長郵箱:is@yisu.com進行舉報,并提供相關(guān)證據(jù),一經(jīng)查實,將立刻刪除涉嫌侵權(quán)內(nèi)容。

AI