什麼是JSON?

JSON是一種數據交換的標準格式,它受到JavaScript的啟發。通常,JSON採用字元串或文本格式。json代表javascript對象表示法。

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

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

JSON與Python字典非常相似。python支持JSON,它有一個內置的庫作為JSON

SON庫的Python

是元帥和泡菜是在外部maintain modules of version of JSON的Python庫。相關業務的性能和解碼JSON編碼的Python類You need to json圖書館和第一進出口文件在你的.py for that,

import json

Following methods are available in the JSON modul

在讀取JSON文件時解碼

Python到JSON(編碼)

默認情況下,JSON Library of Python執行以下Python對象轉換為JSON對象

將Python數據轉換為JSON稱為編碼操作。編碼是在JSON庫方法的幫助下完成的 - dumps() dumps()方法將python的字典對象轉換為JSON字元串數據格式。

現在讓我們用Python執行我們的第一個編碼示例。

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}})

讓我們使用相同的函數dump()創建字典的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)

輸出:

無需顯示...在您的系統中創建了json_file.json,您可以檢查該文件。

JSON到Python(解碼)

JSON字元串解碼是在Python的JSON庫的內置方法load()和load()的幫助下完成的。這裡的轉換表顯示了Python對象的JSON對象示例,這些對象有助於在Python中執行JSON字元串解碼。

讓我們看看在json.loads()函數的幫助下在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)相關的操作。JSON文件必須存在於您指定的程序中指定位置的系統上。

例:

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)

這裡的數據是Python的字典對象。

輸出:

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

Python中的緊湊編碼

當您需要減小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
}

為了更好地理解這一點,將縮進更改為40並觀察輸出 -

訂購JSON代碼:

dumps中的sort_keys屬性函數的參數將按升序對JSON中的鍵進行排序。sort_keys參數是一個布爾屬性。當它是真正的排序時,否則不允許

例:

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的複雜對象編碼

Complex對象有兩個不同的部分

  1. 真實的部分
  2. 想像中的一部分

在執行複雜對象的編碼之前,需要檢查變數是否複雜。您需要創建一個函數,該函數使用實例方法檢查存儲在變數中的值。

讓我們為check對象創建特定的函數是複雜的還是有資格進行編碼。

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中的複雜JSON對象解碼

要在JSON中解碼複雜對象,請使用object_hook參數,該參數檢查JSON字元串是否包含複雜對象。

例:

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 its 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類用於在執行編碼時對任何Python對象進行序列化。它包含三種不同的編碼方法

  • default(o) - 在子類中實現並返回o對象的serialize 對象。
  • encode(o) - 與json.dumps()方法相同,返回Python數據結構的JSON字元串。
  • iterencode(o) - 逐個表示字元串並編碼對象o。

藉助JSONEncoder類的encode()方法,我們還可以對任何Python對象進行編碼。

# 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類用於在執行解碼時對任何Python對象進行反序列化。它包含三種不同的解碼方法

  • default(o) - 在子類中實現並返回反序列化的對象o對象。
  • decode(o) - 與json.loads()方法相同,返回JSON字元串或數據的Python數據結構。
  • 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數據:Real Life Example

我們將從指定的URL(feeds.citibikenyc.com/s)獲取CityBike NYC(自行車共享系統)的數據並轉換為字典格式。

例:

注意: - 確保已在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庫相關的異常:

  • 類json.JSONDecoderError處理與解碼操作相關的異常。它是ValueError的子類。
  • 異常 - json.JSONDecoderError(msg,doc)
  • 異常參數是,
    • msg - 未格式化的錯誤消息

    • doc - 解析JSON文檔
    • pos - 失敗時的doc開始索引

    • lineno - line no shows對應pos
    • 冒號 - 列對應於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數字

JSON數據交換格式(RFC - Request For Comments)不允許無限值或Nan值,但Python-JSON庫中沒有限制執行無限和Nan值相關操作。如果JSON獲得INFINITE和Nan數據類型,則將其轉換為文字。

例:

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字元串中的重複鍵

RFC指定密鑰名稱在JSON對象中應該是唯一的,但它不是必需的。Python JSON庫不會引發JSON中重複對象的異常。它忽略所有重複的鍵值對,並僅考慮它們中的最後一個鍵值對。

例:

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

輸出:

{a: 3}

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

json.tool提供命令行界面來驗證JSON漂亮的列印語法。我們來看一個CLI的例子

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

輸出:

{
"name": " Kings Authur "
}

Python中JSON的優點

  • 容易在容器和值之間移回(JSON到Python和Python到JSON)
  • 人類可讀(漂亮列印)JSON對象
  • 廣泛用於數據處理。
  • 單個文件中沒有相同的數據結構。

Python中JSON的實現限制

  • 在JSON範圍的解串器和預測數字
  • JSON字元串的最大長度和JSON數組以及對象的嵌套級別。

Cheat Code

本次分享到這裡,歡迎評論留言!

推薦閱讀:

相關文章