Python JSON:編碼(轉(zhuǎn)儲)夫植,解碼(加載)json數(shù)據(jù)和文件(示例)

什么是JSON讹剔?

??JSON是一種數(shù)據(jù)交換的標(biāo)準(zhǔn)格式油讯,它受到JavaScript的啟發(fā)。通常延欠,JSON采用字符串或文本格式陌兑。json代表javascript對象表示法。

??json:json的語法是作為鍵和值對編寫的

{
        "Key":  "Value",
        "Key":  "Value",
} 

??JSON與Python字典非常相似由捎。python支持JSON兔综,它有一個內(nèi)置的庫作為JSON

SON庫的Python

??是元帥和泡菜是在外部maintain modules of version of JSON的Python庫。相關(guān)業(yè)務(wù)的性能和解碼JSON編碼的Python類You need to json圖書館和第一進(jìn)出口文件在你的.py for that狞玛,

import json

??Following methods are available in the JSON module

方法 描述
dumps() 編碼為JSON對象
dump() 編碼的字符串寫在文件上
loads() 解碼JSON字符串
load() 在讀取JSON文件時解碼

Python到JSON(編碼)

??默認(rèn)情況下软驰,JSON Library of Python執(zhí)行以下Python對象轉(zhuǎn)換為JSON對象

Python JSON
dict Object
list Array
unicode String
number - int, long number – int
float number – real
True True
False False
None Null

??將Python數(shù)據(jù)轉(zhuǎn)換為JSON稱為編碼操作。編碼是在JSON庫方法的幫助下完成的 - dumps()
??dumps()方法將python的字典對象轉(zhuǎn)換為JSON字符串?dāng)?shù)據(jù)格式心肪。

現(xiàn)在讓我們用Python執(zhí)行我們的第一個編碼示例锭亏。

import json

x = {
  "name": "Ken",
  "age": 45,
  "married": True,
  "children": ("Alice","Bob"),
  "pets": ['Dog'],
  "cars": [
    {"model": "Audi A1", "mpg": 15.1},
    {"model": "Zeep Compass", "mpg": 18.1}
  ]
}
# sorting result in asscending order by keys:
sorted_string = json.dumps(x, indent=4, sort_keys=True)
print(sorted_string)

輸出:

{“person”:{“name”:“Kenn”,“sex”:“male”硬鞍,“age”:28}})

??讓我們使用相同的函數(shù)dump()創(chuàng)建字典的JSON文件

# here we create new data_file.json file with write mode using file i/o operation 
with open('json_file.json', "w") as file_write:
# write json data into file
json.dump(person_data, file_write)

輸出:

??無需顯示...在您的系統(tǒng)中創(chuàng)建了json_file.json慧瘤,您可以檢查該文件。

JSON到Python(解碼)

??JSON字符串解碼是在Python的JSON庫的內(nèi)置方法load()和load()的幫助下完成的固该。這里的轉(zhuǎn)換表顯示了Python對象的JSON對象示例锅减,這些對象有助于在Python中執(zhí)行JSON字符串解碼。

JSON Python
Object dict
Array list
String unicode
number – int number - int, long
number – real float
True True
False False
Null None

??讓我們看看在json.loads()函數(shù)的幫助下在Python中解碼的基本示例

import json  # json library imported
# json data string
person_data = '{  "person":  { "name":  "Kenn",  "sex":  "male",  "age":  28}}'
# Decoding or converting JSON format in dictionary using loads()
dict_obj = json.loads(person_data)
print(dict_obj)
# check type of dict_obj
print("Type of dict_obj", type(dict_obj))
# get human object details
print("Person......",  dict_obj.get('person'))

輸出:

{'person': {'name': 'Kenn', 'sex': 'male', 'age': 28}}
Type of dict_obj <class 'dict'>
Person...... {'name': 'John', 'sex': 'male'}

解碼JSON文件或解析Python中的JSON文件

??注意:解碼JSON文件是文件輸入/輸出(I / O)相關(guān)的操作伐坏。JSON文件必須存在于您指定的程序中指定位置的系統(tǒng)上上煤。

例:

import json
#File I/O Open function for read data from JSON File
with open('X:/json_file.json') as file_object:
        # store file data in object
        data = json.load(file_object)
print(data)

??這里的數(shù)據(jù)是Python的字典對象。

輸出:

{'person': {'name': 'Kenn', 'sex': 'male', 'age': 28}}

Python中的緊湊編碼

??當(dāng)您需要減小JSON文件的大小時著淆,可以在Python中使用緊湊編碼劫狠。

例:

import json
# Create a List that contains dictionary
lst = ['a', 'b', 'c',{'4': 5, '6': 7}]
# separator used for compact representation of JSON.
# Use of ',' to identify list items
# Use of ':' to identify key and value in dictionary
compact_obj = json.dumps(lst, separators=(',', ':'))
print(compact_obj)

輸出:

'["a", "b", "c", {"4": 5, "6": 7}]'

Here output of JSON is represented in a single line which is the most compact representation by
 removing the space character from compact_obj

格式化JSON代碼(漂亮打印)

??目的是為人類理解編寫格式良好的代碼永部。借助漂亮的打印功能独泞,任何人都可以輕松理解代碼。
例:

import json
dic = { 'a': 4, 'b': 5 }
''' To format the code use of indent and 4 shows number of space and use of separator is not 
necessary but standard way to write code of particular function. '''
formatted_obj = json.dumps(dic, indent=4, separators=(',', ': '))
print(formatted_obj)

輸出:

{
   "a" : 4,
   "b" : 5
}

為了更好地理解這一點(diǎn)苔埋,將縮進(jìn)更改為40并觀察輸出 -

訂購JSON代碼:

??dumps中的sort_keys屬性函數(shù)的參數(shù)將按升序?qū)SON中的鍵進(jìn)行排序懦砂。sort_keys參數(shù)是一個布爾屬性。當(dāng)它是真正的排序時组橄,否則不允許

例:

import json

x = {
  "name": "Ken",
  "age": 45,
  "married": True,
  "children": ("Alice", "Bob"),
  "pets": [ 'Dog' ],
  "cars": [
    {"model": "Audi A1", "mpg": 15.1},
    {"model": "Zeep Compass", "mpg": 18.1}
    ],
}
# sorting result in asscending order by keys:
sorted_string = json.dumps(x, indent=4, sort_keys=True)
print(sorted_string)

輸出:

{
    "age": 45,
    "cars": [ {
        "model": "Audi A1", 
        "mpg": 15.1
    },
    {
        "model": "Zeep Compass", 
        "mpg": 18.1
    }
    ],
    "children": [ "Alice",
          "Bob"
    ],
    "married": true,
    "name": "Ken",
    "pets": [ 
        "Dog"
    ]
}

您可能會看到鑰匙的年齡荞膘,汽車,兒童等按升序排列玉工。

Python的復(fù)雜對象編碼

Complex對象有兩個不同的部分

  1. 真實(shí)的部分
  2. 想象中的一部分

??在執(zhí)行復(fù)雜對象的編碼之前羽资,需要檢查變量是否復(fù)雜。您需要創(chuàng)建一個函數(shù)遵班,該函數(shù)使用實(shí)例方法檢查存儲在變量中的值屠升。

??讓我們?yōu)閏heck對象創(chuàng)建特定的函數(shù)是復(fù)雜的還是有資格進(jìn)行編碼潮改。

import json

# create function to check instance is complex or not
def complex_encode(object):
    # check using isinstance method
    if isinstance(object, complex):
        return [object.real, object.imag]
    # raised error using exception handling if object is not complex
    raise TypeError(repr(object) + " is not JSON serialized")


# perform json encoding by passing parameter
complex_obj = json.dumps(4 + 5j, default=complex_encode)
print(complex_obj)

輸出:

'[4.0, 5.0]'

Python中的復(fù)雜JSON對象解碼

??要在JSON中解碼復(fù)雜對象,請使用object_hook參數(shù)腹暖,該參數(shù)檢查JSON字符串是否包含復(fù)雜對象汇在。

例:

import json
  # function check JSON string contains complex object
  def is_complex(objct):
    if '__complex__' in objct:
      return complex(objct['real'], objct['img'])
    return objct
  
  # use of json loads method with object_hook for check object complex or not
  complex_object =json.loads('{"__complex__": true, "real": 4, "img": 5}', object_hook = is_complex)
  #here we not passed complex object so it's convert into dictionary
  simple_object =json.loads('{"real": 6, "img": 7}', object_hook = is_complex)
  print("Complex_object......",complex_object)
  print("Without_complex_object......",simple_object)

輸出:

Complex_object...... (4+5j)
Without_complex_object...... {'real': 6, 'img': 7}

JSON序列化類JSONEncoder概述

??JSONEncoder類用于在執(zhí)行編碼時對任何Python對象進(jìn)行序列化。它包含三種不同的編碼方法

  • default(o) - 在子類中實(shí)現(xiàn)并返回o對象的serialize 對象脏答。
  • encode(o) - 與json.dumps()方法相同糕殉,返回Python數(shù)據(jù)結(jié)構(gòu)的JSON字符串。
  • iterencode(o) - 逐個表示字符串并編碼對象o殖告。

??借助JSONEncoder類的encode()方法阿蝶,我們還可以對任何Python對象進(jìn)行編碼。

# import JSONEncoder class from json
from json.encoder import JSONEncoder
colour_dict = { "colour": ["red", "yellow", "green" ]}
# directly called encode method of JSON
JSONEncoder().encode(colour_dict)
Output:

輸出:

'{"colour": ["red", "yellow", "green"]}'

JSON反序列化類JSONDecoder概述

??JSONDecoder類用于在執(zhí)行解碼時對任何Python對象進(jìn)行反序列化丛肮。它包含三種不同的解碼方法

  • default(o) - 在子類中實(shí)現(xiàn)并返回反序列化的對象o對象赡磅。
  • decode(o) - 與json.loads()方法相同,返回JSON字符串或數(shù)據(jù)的Python數(shù)據(jù)結(jié)構(gòu)宝与。
  • raw_decode(o) - 逐個表示Python字典并解碼對象o焚廊。

??借助JSONDecoder類的decode()方法,我們還可以解碼JSON字符串习劫。

import json
# import JSONDecoder class from json
from json.decoder import JSONDecoder
colour_string = '{ "colour": ["red", "yellow"]}'
# directly called decode method of JSON
JSONDecoder().decode(colour_string)

輸出:

{'colour': ['red', 'yellow']}

從URL解碼JSON數(shù)據(jù):Real Life Example

我們將從指定的URL(https://feeds.citibikenyc.com/stations/stations.json)獲取CityBike NYC(自行車共享系統(tǒng))的數(shù)據(jù)并轉(zhuǎn)換為字典格式咆瘟。

例:

注意: - 確保已在Python中安裝了請求庫,如果沒有诽里,則打開終端或CMD并鍵入

  • (對于Python 3或更高版本)pip3安裝請求
import json
import requests

# get JSON string data from CityBike NYC using web requests library
json_response= requests.get("https://feeds.citibikenyc.com/stations/stations.json")
# check type of json_response object
print(type(json_response.text))
# load data in loads() function of json library
bike_dict = json.loads(json_response.text)
#check type of news_dict
print(type(bike_dict))
# now get stationBeanList key data from dict
print(bike_dict['stationBeanList'][0]) 

輸出:

<class 'str'>
<class 'dict'>
{
    'id': 487,
    'stationName': 'E 20 St & FDR Drive',
    'availableDocks': 24,
    'totalDocks': 34,
    'latitude': 40.73314259,
    'longitude': -73.97573881,
    'statusValue': 'In Service',
    'statusKey': 1,
    'availableBikes': 9,
    'stAddress1': 'E 20 St & FDR Drive',
    'stAddress2': '',
    'city': '',
    'postalCode': '',
    'location': '', 
    'altitude': '', 
    'testStation': False, 
    'lastCommunicationTime': '2018-12-11 10:59:09 PM', 'landMark': ''
}

與Python中的JSON庫相關(guān)的異常:

  • 類json.JSONDecoderError處理與解碼操作相關(guān)的異常袒餐。它是ValueError的子類。
  • 異常 - json.JSONDecoderError(msg谤狡,doc)
  • 異常參數(shù)是灸眼,
    • msg - 未格式化的錯誤消息
    • doc - 解析JSON文檔
    • pos - 失敗時的doc開始索引
    • lineno - line no shows對應(yīng)pos
    • 冒號 - 列對應(yīng)于pos

例:

import json
#File I/O Open function for read data from JSON File
data = {} #Define Empty Dictionary Object
try:
        with open('json_file_name.json') as file_object:
                data = json.load(file_object)
except ValueError:
     print("Bad JSON file format,  Change JSON File")

Python中的無限和NaN數(shù)字

??JSON數(shù)據(jù)交換格式(RFC - Request For Comments)不允許無限值或Nan值,但Python-JSON庫中沒有限制執(zhí)行無限和Nan值相關(guān)操作墓懂。如果JSON獲得INFINITE和Nan數(shù)據(jù)類型焰宣,則將其轉(zhuǎn)換為文字。

例:

import json
# pass float Infinite value
infinite_json = json.dumps(float('inf'))
# check infinite json type
print(infinite_json)
print(type(infinite_json))
json_nan = json.dumps(float('nan'))
print(json_nan)
# pass json_string as Infinity
infinite = json.loads('Infinity')
print(infinite)
# check type of Infinity
print(type(infinite))

輸出:

Infinity
<class 'str'>
NaN
inf
<class 'float'> 

JSON字符串中的重復(fù)鍵

??RFC指定密鑰名稱在JSON對象中應(yīng)該是唯一的捕仔,但它不是必需的匕积。Python JSON庫不會引發(fā)JSON中重復(fù)對象的異常。它忽略所有重復(fù)的鍵值對榜跌,并僅考慮它們中的最后一個鍵值對闪唆。

例:

import json
repeat_pair = '{"a":  1, "a":  2, "a":  3}'
json.loads(repeat_pair)

輸出:

{'a': 3}

在Python中使用JSON的CLI(命令行界面)

??json.tool提供命令行界面來驗(yàn)證JSON漂亮的打印語法。我們來看一個CLI的例子

$ echo '{"name" : "Kings Authur" }' | python3 -m json.tool

輸出:

{
    "name": " Kings Authur "
}

Python中JSON的優(yōu)點(diǎn)

  • 容易在容器和值之間移回(JSON到Python和Python到JSON)
  • 人類可讀(漂亮打拥龊)JSON對象
  • 廣泛用于數(shù)據(jù)處理悄蕾。
  • 單個文件中沒有相同的數(shù)據(jù)結(jié)構(gòu)。

Python中JSON的實(shí)現(xiàn)限制

  • 在JSON范圍的解串器和預(yù)測數(shù)字
  • JSON字符串的最大長度和JSON數(shù)組以及對象的嵌套級別瓤逼。

Cheat Code

json.dumps(person_data) 創(chuàng)建JSON對象
json.dump(person_data, file_write) 使用Python的File I / O創(chuàng)建JSON文件
compact_obj = json.dumps(data, separators=(',',':')) 通過使用分隔符從JSON對象中刪除空格字符來壓縮JSON對象
formatted_obj = json.dumps(dic, indent=4, separators=(',', ': ')) 使用Indent格式化JSON代碼
sorted_string = json.dumps(x, indent=4, sort_keys=True) 按字母順序?qū)SON對象鍵進(jìn)行排序
complex_obj = json.dumps(4 + 5j, default=complex_encode) JSON中的Python復(fù)雜對象編碼
JSONEncoder().encode(colour_dict) 使用JSONEncoder類進(jìn)行序列化
json.loads(data_string) 使用json.loads()函數(shù)解碼Python字典中的JSON字符串
json.loads('{"complex": true, "real": 4, "img": 5}', object_hook = is_complex) 將復(fù)雜的JSON對象解碼為Python
JSONDecoder().decode(colour_string) 使用反序列化將JSON解碼到Python

本次分享到這里笼吟,歡迎評論留言库物!

?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
  • 序言:七十年代末霸旗,一起剝皮案震驚了整個濱河市贷帮,隨后出現(xiàn)的幾起案子,更是在濱河造成了極大的恐慌诱告,老刑警劉巖撵枢,帶你破解...
    沈念sama閱讀 222,252評論 6 516
  • 序言:濱河連續(xù)發(fā)生了三起死亡事件,死亡現(xiàn)場離奇詭異精居,居然都是意外死亡锄禽,警方通過查閱死者的電腦和手機(jī),發(fā)現(xiàn)死者居然都...
    沈念sama閱讀 94,886評論 3 399
  • 文/潘曉璐 我一進(jìn)店門靴姿,熙熙樓的掌柜王于貴愁眉苦臉地迎上來沃但,“玉大人,你說我怎么就攤上這事佛吓∠恚” “怎么了?”我有些...
    開封第一講書人閱讀 168,814評論 0 361
  • 文/不壞的土叔 我叫張陵维雇,是天一觀的道長淤刃。 經(jīng)常有香客問我,道長吱型,這世上最難降的妖魔是什么逸贾? 我笑而不...
    開封第一講書人閱讀 59,869評論 1 299
  • 正文 為了忘掉前任,我火速辦了婚禮津滞,結(jié)果婚禮上铝侵,老公的妹妹穿的比我還像新娘。我一直安慰自己触徐,他們只是感情好咪鲜,可當(dāng)我...
    茶點(diǎn)故事閱讀 68,888評論 6 398
  • 文/花漫 我一把揭開白布。 她就那樣靜靜地躺著锌介,像睡著了一般嗜诀。 火紅的嫁衣襯著肌膚如雪。 梳的紋絲不亂的頭發(fā)上孔祸,一...
    開封第一講書人閱讀 52,475評論 1 312
  • 那天隆敢,我揣著相機(jī)與錄音,去河邊找鬼崔慧。 笑死拂蝎,一個胖子當(dāng)著我的面吹牛,可吹牛的內(nèi)容都是我干的惶室。 我是一名探鬼主播温自,決...
    沈念sama閱讀 41,010評論 3 422
  • 文/蒼蘭香墨 我猛地睜開眼玄货,長吁一口氣:“原來是場噩夢啊……” “哼!你這毒婦竟也來了悼泌?” 一聲冷哼從身側(cè)響起松捉,我...
    開封第一講書人閱讀 39,924評論 0 277
  • 序言:老撾萬榮一對情侶失蹤,失蹤者是張志新(化名)和其女友劉穎馆里,沒想到半個月后隘世,有當(dāng)?shù)厝嗽跇淞掷锇l(fā)現(xiàn)了一具尸體,經(jīng)...
    沈念sama閱讀 46,469評論 1 319
  • 正文 獨(dú)居荒郊野嶺守林人離奇死亡鸠踪,尸身上長有42處帶血的膿包…… 初始之章·張勛 以下內(nèi)容為張勛視角 年9月15日...
    茶點(diǎn)故事閱讀 38,552評論 3 342
  • 正文 我和宋清朗相戀三年丙者,在試婚紗的時候發(fā)現(xiàn)自己被綠了。 大學(xué)時的朋友給我發(fā)了我未婚夫和他白月光在一起吃飯的照片营密。...
    茶點(diǎn)故事閱讀 40,680評論 1 353
  • 序言:一個原本活蹦亂跳的男人離奇死亡械媒,死狀恐怖,靈堂內(nèi)的尸體忽然破棺而出评汰,到底是詐尸還是另有隱情纷捞,我是刑警寧澤,帶...
    沈念sama閱讀 36,362評論 5 351
  • 正文 年R本政府宣布键俱,位于F島的核電站兰绣,受9級特大地震影響,放射性物質(zhì)發(fā)生泄漏编振。R本人自食惡果不足惜缀辩,卻給世界環(huán)境...
    茶點(diǎn)故事閱讀 42,037評論 3 335
  • 文/蒙蒙 一、第九天 我趴在偏房一處隱蔽的房頂上張望踪央。 院中可真熱鬧臀玄,春花似錦、人聲如沸畅蹂。這莊子的主人今日做“春日...
    開封第一講書人閱讀 32,519評論 0 25
  • 文/蒼蘭香墨 我抬頭看了看天上的太陽液斜。三九已至累贤,卻和暖如春,著一層夾襖步出監(jiān)牢的瞬間少漆,已是汗流浹背臼膏。 一陣腳步聲響...
    開封第一講書人閱讀 33,621評論 1 274
  • 我被黑心中介騙來泰國打工, 沒想到剛下飛機(jī)就差點(diǎn)兒被人妖公主榨干…… 1. 我叫王不留示损,地道東北人渗磅。 一個月前我還...
    沈念sama閱讀 49,099評論 3 378
  • 正文 我出身青樓,卻偏偏與公主長得像,于是被迫代替她去往敵國和親始鱼。 傳聞我的和親對象是個殘疾皇子仔掸,可洞房花燭夜當(dāng)晚...
    茶點(diǎn)故事閱讀 45,691評論 2 361

推薦閱讀更多精彩內(nèi)容