Python JSON: เข้ารหัส (ทิ้ง) ถอดรหัส (โหลด) และอ่านไฟล์ JSON
JSON คืออะไร Python?
JSON in Python เป็นรูปแบบมาตรฐานที่ได้รับแรงบันดาลใจมาจาก Javaสคริปต์สำหรับการแลกเปลี่ยนข้อมูลและการถ่ายโอนข้อมูลในรูปแบบข้อความผ่านเครือข่าย โดยทั่วไป JSON จะอยู่ในรูปแบบสตริงหรือข้อความ สามารถใช้ได้โดย API และฐานข้อมูล และจะแสดงวัตถุเป็นคู่ชื่อ/ค่า JSON ย่อมาจาก Javaสัญกรณ์วัตถุสคริปต์
Python ไวยากรณ์ JSON:
JSON เขียนเป็นคู่คีย์และค่า
{ "Key": "Value", "Key": "Value", }
JSON คล้ายกันมากกับ Python พจนานุกรม. Python รองรับ JSON และมีไลบรารี่ในตัวเป็น JSON
ไลบรารี JSON ใน Python
'จอมพล'และ'ดอง' โมดูลภายนอกของ Python รักษาเวอร์ชันของ JSON Python ห้องสมุด. การทำงานร่วมกับ JSON ใน Python ในการดำเนินการที่เกี่ยวข้องกับ JSON เช่น การเข้ารหัสและถอดรหัส คุณต้องทำสิ่งต่อไปนี้ก่อน นำเข้า ไลบรารี JSON และสำหรับสิ่งนั้นใน .py ไฟล์,
import json
วิธีการต่อไปนี้มีอยู่ใน JSON Python โมดูล
วิธี | Descriptไอออน |
---|---|
ทิ้ง() | การเข้ารหัสไปยังวัตถุ JSON |
ดัมพ์() | การเขียนสตริงที่เข้ารหัสลงในไฟล์ |
โหลด() | ถอดรหัสสตริง JSON |
โหลด() | ถอดรหัสในขณะที่อ่านไฟล์ JSON |
Python เป็น JSON (การเข้ารหัส)
JSON ห้องสมุดของ Python ดำเนินการแปลดังต่อไปนี้ Python วัตถุลงในวัตถุ JSON ตามค่าเริ่มต้น
Python | JSON |
---|---|
Dict | วัตถุ |
รายการ | แถว |
Unicode | เชือก |
หมายเลข – int ยาว | หมายเลข – int |
ลอย | หมายเลข – จริง |
จริง | จริง |
เท็จ | เท็จ |
ไม่มี | โมฆะ |
แปลง Python ข้อมูลเป็น JSON เรียกว่าการดำเนินการเข้ารหัส การเข้ารหัสทำได้ด้วยความช่วยเหลือของวิธีไลบรารี JSON ทิ้ง()
JSON ทิ้ง () ใน Python
json.dumps() in Python เป็นวิธีการแปลงวัตถุพจนานุกรมของ Python เป็นรูปแบบข้อมูลสตริง JSON ซึ่งมีประโยชน์เมื่อวัตถุต้องอยู่ในรูปแบบสตริงสำหรับการดำเนินการ เช่น การแยกวิเคราะห์ การพิมพ์ เป็นต้น
ตอนนี้เรามาดำเนินการตัวอย่างการเข้ารหัส json.dumps แรกของเราด้วย 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)
Output:
{"person": {"name": "Kenn", "sex": "male", "age": 28}})
เรามาดูตัวอย่างกัน Python เขียน JSON ลงในไฟล์เพื่อสร้างไฟล์ 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)
Output:
ไม่มีสิ่งใดที่จะแสดง...ในระบบของคุณมีการสร้าง json_file.json แล้ว คุณสามารถตรวจสอบไฟล์นั้นได้ดังแสดงในด้านล่างเขียน JSON ไปยังไฟล์ Python ตัวอย่าง.
JSON ถึง Python (ถอดรหัส)
การถอดรหัสสตริง JSON ทำได้โดยใช้วิธี inbuilt json.โหลด() & json.โหลด() ของไลบรารี JSON ใน Python- ตารางการแปลที่นี่แสดงตัวอย่างของวัตถุ JSON ถึง Python วัตถุ ซึ่งมีประโยชน์ในการถอดรหัส Python ของสตริง JSON
JSON | Python |
---|---|
วัตถุ | Dict |
แถว | รายการ |
เชือก | Unicode |
หมายเลข – int | หมายเลข – int ยาว |
หมายเลข – จริง | ลอย |
จริง | จริง |
เท็จ | เท็จ |
โมฆะ | ไม่มี |
มาดูการแยกวิเคราะห์ JSON พื้นฐานกัน Python ตัวอย่างการถอดรหัสด้วยความช่วยเหลือของ json.โหลด ฟังก์ชั่น
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'))
Output:
{'person': {'name': 'Kenn', 'sex': 'male', 'age': 28}} Type of dict_obj <class 'dict'> Person...... {'name': 'John', 'sex': 'male'}
ถอดรหัสไฟล์ JSON หรือแยกวิเคราะห์ไฟล์ JSON Python
ตอนนี้เราจะเรียนรู้วิธีการอ่านไฟล์ JSON Python กับ Python แยกตัวอย่าง JSON:
หมายเหตุ: การถอดรหัสไฟล์ JSON คือการดำเนินการที่เกี่ยวข้องกับอินพุต/เอาต์พุตไฟล์ (I/O) ไฟล์ JSON จะต้องมีอยู่ในระบบของคุณในตำแหน่งที่ระบุในโปรแกรมของคุณ
Python อ่านไฟล์ 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 ดังที่แสดงในไฟล์ JSON อ่านด้านบน Python ตัวอย่าง.
Output:
{'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)
Output:
'["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)
Output:
{ "a" : 4, "b" : 5 }
เพื่อให้เข้าใจสิ่งนี้ได้ดีขึ้น ให้เปลี่ยนการเยื้องเป็น 40 และสังเกตผลลัพธ์
การสั่งซื้อรหัส JSON:
sort_keys แอตทริบิวต์ใน Python อาร์กิวเมนต์ของฟังก์ชัน dumps จะเรียงลำดับคีย์ใน JSON ตามลำดับจากน้อยไปมาก อาร์กิวเมนต์ sort_keys เป็นแอตทริบิวต์บูลีน เมื่อเป็นจริงจะอนุญาตให้เรียงลำดับได้ มิฉะนั้นจะไม่อนุญาตให้เรียงลำดับ มาทำความเข้าใจกันด้วย Python ตัวอย่างการเรียงลำดับสตริงเป็น JSON
ตัวอย่าง,
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)
Output:
{ "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
วัตถุที่ซับซ้อนมีสองส่วนที่แตกต่างกันคือ
- ส่วนจริง
- ส่วนจินตภาพ
ตัวอย่าง: 3 +2i
ก่อนที่จะทำการเข้ารหัสอ็อบเจ็กต์ที่ซับซ้อน คุณต้องตรวจสอบตัวแปรก่อนว่าซับซ้อนหรือไม่ คุณต้องสร้างฟังก์ชันที่ตรวจสอบค่าที่จัดเก็บไว้ในตัวแปรโดยใช้เมธอดอินสแตนซ์
ให้สร้างฟังก์ชันเฉพาะเพื่อตรวจสอบว่าวัตถุมีความซับซ้อนหรือมีสิทธิ์เข้ารหัสหรือไม่
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)
Output:
'[4.0, 5.0]'
การถอดรหัสวัตถุ JSON ที่ซับซ้อนใน Python
ในการถอดรหัสอ็อบเจ็กต์ที่ซับซ้อนใน JSON ให้ใช้พารามิเตอร์ object_hook ซึ่งจะตรวจสอบว่าสตริง JSON มีอ็อบเจ็กต์ที่ซับซ้อนหรือไม่ มาทำความเข้าใจกับสตริงใน JSON กัน Python ตัวอย่าง,
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)
Output:
Complex_object...... (4+5j) Without_complex_object...... {'real': 6, 'img': 7}
ภาพรวมของคลาส JSON Serialization JSONEncoder
คลาส JSONEncoder ใช้สำหรับการทำให้เป็นอันดับใด ๆ Python วัตถุขณะทำการเข้ารหัส ประกอบด้วยวิธีการเข้ารหัสที่แตกต่างกัน 3 วิธี ได้แก่
- ค่าเริ่มต้น (o) – นำไปใช้ในคลาสย่อยและส่งคืนอ็อบเจ็กต์ซีเรียลไลซ์สำหรับ o วัตถุ.
- เข้ารหัส(o) – เช่นเดียวกับการดัมพ์ JSON Python วิธีการส่งคืนสตริง JSON ของ Python โครงสร้างข้อมูล.
- รหัสซ้ำ(o) – แสดงสตริงทีละรายการและเข้ารหัสอ็อบเจ็กต์ o
ด้วยความช่วยเหลือของวิธีการ encode() ของคลาส JSONEncoder เรายังสามารถเข้ารหัสใดๆ ก็ได้ Python วัตถุดังแสดงด้านล่าง Python ตัวอย่างตัวเข้ารหัส JSON
# 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 วัตถุขณะทำการถอดรหัส ประกอบด้วยวิธีการถอดรหัส 3 วิธี ได้แก่
- ค่าเริ่มต้น (o) – นำไปใช้ในคลาสย่อยและส่งคืนอ็อบเจ็กต์ดีซีเรียลไลซ์ o วัตถุ.
- ถอดรหัส(o) – เช่นเดียวกับการส่งคืนเมธอด json.loads() Python โครงสร้างข้อมูลของสตริงหรือข้อมูล JSON
- raw_decode(o) - แทน Python พจนานุกรมทีละรายการและถอดรหัสวัตถุ o
ด้วยความช่วยเหลือของเมธอด decode() ของคลาส JSONDecoder เรายังสามารถถอดรหัสสตริง JSON ดังแสดงด้านล่าง Python ตัวอย่างตัวถอดรหัส 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)
Output:
{'colour': ['red', 'yellow']}
การถอดรหัสข้อมูล JSON จาก URL: ตัวอย่างชีวิตจริง
เราจะดึงข้อมูลของ CityBike NYC (Bike Sharing System) จาก URL ที่ระบุ (https://gbfs.citibikenyc.com/gbfs/2.3/gbfs.json) และแปลงเป็นรูปแบบพจนานุกรม
Python โหลด JSON จากไฟล์ตัวอย่าง:
หมายเหตุ: - ตรวจสอบให้แน่ใจว่าไลบรารีคำขอได้รับการติดตั้งแล้วในของคุณ Pythonถ้าไม่เช่นนั้นให้เปิด Terminal หรือ CMD แล้วพิมพ์
- (สำหรับ Python 3 หรือสูงกว่า) คำขอติดตั้ง pip3
import json import requests # get JSON string data from CityBike NYC using web requests library json_response= requests.get("https://gbfs.citibikenyc.com/gbfs/2.3/gbfs.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])
Output:
<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': '' }
ข้อยกเว้นที่เกี่ยวข้องกับไลบรารี JSON ใน Python:
- ชั้น json.JSONDecoderข้อผิดพลาด จัดการข้อยกเว้นที่เกี่ยวข้องกับการดำเนินการถอดรหัส และเป็นคลาสย่อยของ ค่าข้อผิดพลาด
- ข้อยกเว้น – json.JSONDecoderError (ข้อความ, doc)
- พารามิเตอร์ของข้อยกเว้นคือ
- msg – ข้อความแสดงข้อผิดพลาดที่ไม่ได้ฟอร์แมต
- doc – เอกสาร JSON แยกวิเคราะห์แล้ว
- pos – เริ่มดัชนีของ doc เมื่อล้มเหลว
- lineno – บรรทัดไม่แสดงตรงกับตำแหน่ง
- เครื่องหมายทวิภาค – คอลัมน์ไม่ตรงกับตำแหน่ง
Python โหลด JSON จากไฟล์ตัวอย่าง:
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")
อนันต์และน่าน Numbers in Python
รูปแบบการแลกเปลี่ยนข้อมูล JSON (RFC – ขอความคิดเห็น) ไม่อนุญาตให้ใช้ค่าอนันต์หรือน่าน แต่ไม่มีข้อจำกัดใน 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))
Output:
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)
Output:
{'a': 3}
CLI (อินเทอร์เฟซบรรทัดคำสั่ง) พร้อม JSON ใน Python
json.เครื่องมือ จัดเตรียมอินเทอร์เฟซบรรทัดคำสั่งเพื่อตรวจสอบความถูกต้องของไวยากรณ์ JSON Pretty-Print มาดูตัวอย่าง CLI กัน
$ echo '{"name" : "Kings Authur" }' | python3 -m json.tool
Output:
{ "name": " Kings Authur " }
ข้อดีของ JSON ใน Python
- ง่ายต่อการย้ายกลับระหว่างคอนเทนเนอร์และค่า (JSON to Python และ Python เป็น JSON)
- วัตถุ JSON ที่มนุษย์สามารถอ่านได้ (Pretty-print)
- ใช้กันอย่างแพร่หลายในการจัดการข้อมูล
- ไม่มีโครงสร้างข้อมูลเดียวกันในไฟล์เดียว
ข้อจำกัดในการใช้งาน JSON ใน Python
- ในดีซีเรียลไลเซอร์ของช่วง JSON และการทำนายตัวเลข
- ความยาวสูงสุดของสตริง JSON และอาร์เรย์ของ JSON และระดับการซ้อนของอ็อบเจ็กต์
Python แผ่นโกง JSON
Python ฟังก์ชัน JSON | Descriptไอออน |
---|---|
json.dumps(person_data) | สร้างวัตถุ JSON |
json.dump (person_data, file_write) | สร้างไฟล์ JSON โดยใช้ File I/O ของ Python |
compact_obj = json.dumps (ข้อมูล ตัวคั่น =(',',':')) | กระชับ JSON Object โดยลบอักขระเว้นวรรคออกจาก JSON Object โดยใช้ตัวคั่น |
formatted_obj = json.dumps(dic, indent=4, separators=(',', ': ')) | การจัดรูปแบบโค้ด JSON โดยใช้ Indent |
sorted_string = json.dumps (x, เยื้อง = 4, sort_keys = True) | การเรียงลำดับออบเจ็กต์คีย์ JSON ตามลำดับตัวอักษร |
complex_obj = json.dumps(4 + 5j, ค่าเริ่มต้น=complex_encode) | Python การเข้ารหัสวัตถุที่ซับซ้อนใน JSON |
JSONEncoder().เข้ารหัส(color_dict) | การใช้คลาส JSONEncoder สำหรับการทำให้เป็นอนุกรม |
json.loads(data_string) | ถอดรหัสสตริง JSON ใน Python พจนานุกรมโดยใช้ฟังก์ชัน json.loads() |
json.loads('{“__complex__”: true, “real”: 4, “img”: 5}', object_hook = is_complex) | การถอดรหัสของวัตถุ JSON ที่ซับซ้อน Python |
JSONDecoder().ถอดรหัส(color_string) | การใช้การถอดรหัส JSON เป็น Python ด้วยการดีซีเรียลไลเซชัน |