JSON đến đối tượng Python
Mã follwing tạo các thuộc tính động với các phím đối tượng một cách đệ quy.
Đối tượng JSON - import json class AppConfiguration(object): def __init__(self, data=None): if data is None: with open("fb_data.json") as fh: data = json.loads(fh.read()) else: data = dict(data) for key, val in data.items(): setattr(self, key, self.compute_attr_value(val)) def compute_attr_value(self, value): if isinstance(value, list): return [self.compute_attr_value(x) for x in value] elif isinstance(value, dict): return AppConfiguration(value) else: return value if __name__ == "__main__": instance = AppConfiguration() print(instance.name) print(instance.hometown.name) print(instance.hometown.id) print(instance.list[4].key) print(instance.object.key.key) 6:
{ "name": "John Smith", "hometown": { "name": "New York", "id": 123 }, "list": [ "a", "b", "c", 1, { "key": 1 } ], "object": { "key": { "key": 1 } } }Trên chuyển đổi, chúng tôi có 3 trường hợp:
- danh sách
- Dicts (đối tượng mới)
- bool, int, float và str
Bây giờ khóa, cặp giá trị là các thuộc tính - đối tượng.
output:
John Smith New York 123 1 1Dán JSON làm mã
Hỗ trợ import json class AppConfiguration(object): def __init__(self, data=None): if data is None: with open("fb_data.json") as fh: data = json.loads(fh.read()) else: data = dict(data) for key, val in data.items(): setattr(self, key, self.compute_attr_value(val)) def compute_attr_value(self, value): if isinstance(value, list): return [self.compute_attr_value(x) for x in value] elif isinstance(value, dict): return AppConfiguration(value) else: return value if __name__ == "__main__": instance = AppConfiguration() print(instance.name) print(instance.hometown.name) print(instance.hometown.id) print(instance.list[4].key) print(instance.object.key.key) 7, import json class AppConfiguration(object): def __init__(self, data=None): if data is None: with open("fb_data.json") as fh: data = json.loads(fh.read()) else: data = dict(data) for key, val in data.items(): setattr(self, key, self.compute_attr_value(val)) def compute_attr_value(self, value): if isinstance(value, list): return [self.compute_attr_value(x) for x in value] elif isinstance(value, dict): return AppConfiguration(value) else: return value if __name__ == "__main__": instance = AppConfiguration() print(instance.name) print(instance.hometown.name) print(instance.hometown.id) print(instance.list[4].key) print(instance.object.key.key) 8, import json class AppConfiguration(object): def __init__(self, data=None): if data is None: with open("fb_data.json") as fh: data = json.loads(fh.read()) else: data = dict(data) for key, val in data.items(): setattr(self, key, self.compute_attr_value(val)) def compute_attr_value(self, value): if isinstance(value, list): return [self.compute_attr_value(x) for x in value] elif isinstance(value, dict): return AppConfiguration(value) else: return value if __name__ == "__main__": instance = AppConfiguration() print(instance.name) print(instance.hometown.name) print(instance.hometown.id) print(instance.list[4].key) print(instance.object.key.key) 9, John Smith New York 123 1 1 0, John Smith New York 123 1 1 1, John Smith New York 123 1 1 2, John Smith New York 123 1 1 3, John Smith New York 123 1 1 4, John Smith New York 123 1 1 5, John Smith New York 123 1 1 6, John Smith New York 123 1 1 7, John Smith New York 123 1 1 8, John Smith New York 123 1 1 9, ____.
- Tương tác tạo ra các loại và mã tuần tự hóa (de-)
- Paste JSON/JSON Lược đồ/TypeScript làm mã
# Generated by //quicktype.io # # To change quicktype's target language, run command: # # "Set quicktype target language" from typing import List, Union class Hometown: name: str id: int def __init__(self, name: str, id: int) -> None: self.name = name self.id = id class Key: key: int def __init__(self, key: int) -> None: self.key = key class Object: key: Key def __init__(self, key: Key) -> None: self.key = key class FbData: name: str hometown: Hometown list: List[Union[Key, int, str]] object: Object def __init__(self, name: str, hometown: Hometown, list: List[Union[Key, int, str]], object: Object) -> None: self.name = name self.hometown = hometown self.list = list self.object = object 2 Các loại Infers từ dữ liệu JSON mẫu, sau đó xuất ra các mô hình và các bộ tuần tự được gõ mạnh mẽ để làm việc với dữ liệu đó bằng ngôn ngữ lập trình mong muốn của bạn.
output:
# Generated by //quicktype.io # # To change quicktype's target language, run command: # # "Set quicktype target language" from typing import List, Union class Hometown: name: str id: int def __init__(self, name: str, id: int) -> None: self.name = name self.id = id class Key: key: int def __init__(self, key: int) -> None: self.key = key class Object: key: Key def __init__(self, key: Key) -> None: self.key = key class FbData: name: str hometown: Hometown list: List[Union[Key, int, str]] object: Object def __init__(self, name: str, hometown: Hometown, list: List[Union[Key, int, str]], object: Object) -> None: self.name = name self.hometown = hometown self.list = list self.object = objectTiện ích mở rộng này có sẵn miễn phí trong thị trường Visual Studio Code.
Trong bài viết này, chúng tôi sẽ học cách chuyển đổi dữ liệu JSON thành một đối tượng Python tùy chỉnh. tức là, Parse và chuyển đổi JSON thành lớp Python. Ví dụ: bạn nhận được dữ liệu JSON của nhân viên từ API hoặc bạn đang đọc JSON từ một tệp và muốn chuyển đổi nó thành loại nhân viên tùy chỉnh.learn how to convert JSON data into a custom Python object. i.e., Parse and convert JSON into Python Class. For example, you receive employee JSON data from the API or you are reading JSON from a file and wanted to convert it into a custom Employee type.
Bạn biết cách mã hóa đối tượng Python thành JSON. Khi bạn tải dữ liệu JSON từ tệp hoặc chuỗi bằng phương thức json.load () và json.loads () & nbsp;, nó sẽ trả về # Generated by //quicktype.io # # To change quicktype's target language, run command: # # "Set quicktype target language" from typing import List, Union class Hometown: name: str id: int def __init__(self, name: str, id: int) -> None: self.name = name self.id = id class Key: key: int def __init__(self, key: int) -> None: self.key = key class Object: key: Key def __init__(self, key: Key) -> None: self.key = key class FbData: name: str hometown: Hometown list: List[Union[Key, int, str]] object: Object def __init__(self, name: str, hometown: Hometown, list: List[Union[Key, int, str]], object: Object) -> None: self.name = name self.hometown = hometown self.list = list self.object = object 3.
Nếu chúng tôi tải dữ liệu JSON trực tiếp vào loại tùy chỉnh của chúng tôi, chúng tôi có thể thao tác và sử dụng nó một cách dễ dàng hơn. Có nhiều cách khác nhau để đạt được điều này. Bạn có thể chọn cách bạn thấy nó hữu ích hơn cho vấn đề của mình. Hãy cùng xem cách phân hủy chuỗi JSON vào một đối tượng Python tùy chỉnh.
Sử dụng tên được đặt tên và object_hook để chuyển đổi dữ liệu json thành đối tượng python tùy chỉnh
Chúng ta có thể sử dụng # Generated by //quicktype.io # # To change quicktype's target language, run command: # # "Set quicktype target language" from typing import List, Union class Hometown: name: str id: int def __init__(self, name: str, id: int) -> None: self.name = name self.id = id class Key: key: int def __init__(self, key: int) -> None: self.key = key class Object: key: Key def __init__(self, key: Key) -> None: self.key = key class FbData: name: str hometown: Hometown list: List[Union[Key, int, str]] object: Object def __init__(self, name: str, hometown: Hometown, list: List[Union[Key, int, str]], object: Object) -> None: self.name = name self.hometown = hometown self.list = list self.object = object 4Parameter của phương pháp # Generated by //quicktype.io # # To change quicktype's target language, run command: # # "Set quicktype target language" from typing import List, Union class Hometown: name: str id: int def __init__(self, name: str, id: int) -> None: self.name = name self.id = id class Key: key: int def __init__(self, key: int) -> None: self.key = key class Object: key: Key def __init__(self, key: Key) -> None: self.key = key class FbData: name: str hometown: Hometown list: List[Union[Key, int, str]] object: Object def __init__(self, name: str, hometown: Hometown, list: List[Union[Key, int, str]], object: Object) -> None: self.name = name self.hometown = hometown self.list = list self.object = object 5 và # Generated by //quicktype.io # # To change quicktype's target language, run command: # # "Set quicktype target language" from typing import List, Union class Hometown: name: str id: int def __init__(self, name: str, id: int) -> None: self.name = name self.id = id class Key: key: int def __init__(self, key: int) -> None: self.key = key class Object: key: Key def __init__(self, key: Key) -> None: self.key = key class FbData: name: str hometown: Hometown list: List[Union[Key, int, str]] object: Object def __init__(self, name: str, hometown: Hometown, list: List[Union[Key, int, str]], object: Object) -> None: self.name = name self.hometown = hometown self.list = list self.object = object 6. # Generated by //quicktype.io # # To change quicktype's target language, run command: # # "Set quicktype target language" from typing import List, Union class Hometown: name: str id: int def __init__(self, name: str, id: int) -> None: self.name = name self.id = id class Key: key: int def __init__(self, key: int) -> None: self.key = key class Object: key: Key def __init__(self, key: Key) -> None: self.key = key class FbData: name: str hometown: Hometown list: List[Union[Key, int, str]] object: Object def __init__(self, name: str, hometown: Hometown, list: List[Union[Key, int, str]], object: Object) -> None: self.name = name self.hometown = hometown self.list = list self.object = object 4 là một chức năng tùy chọn sẽ được gọi với kết quả của bất kỳ đối tượng nào được giải mã theo nghĩa đen (một dict). Vì vậy, khi chúng tôi thực thi # Generated by //quicktype.io # # To change quicktype's target language, run command: # # "Set quicktype target language" from typing import List, Union class Hometown: name: str id: int def __init__(self, name: str, id: int) -> None: self.name = name self.id = id class Key: key: int def __init__(self, key: int) -> None: self.key = key class Object: key: Key def __init__(self, key: Key) -> None: self.key = key class FbData: name: str hometown: Hometown list: List[Union[Key, int, str]] object: Object def __init__(self, name: str, hometown: Hometown, list: List[Union[Key, int, str]], object: Object) -> None: self.name = name self.hometown = hometown self.list = list self.object = object 5, giá trị trả về của # Generated by //quicktype.io # # To change quicktype's target language, run command: # # "Set quicktype target language" from typing import List, Union class Hometown: name: str id: int def __init__(self, name: str, id: int) -> None: self.name = name self.id = id class Key: key: int def __init__(self, key: int) -> None: self.key = key class Object: key: Key def __init__(self, key: Key) -> None: self.key = key class FbData: name: str hometown: Hometown list: List[Union[Key, int, str]] object: Object def __init__(self, name: str, hometown: Hometown, list: List[Union[Key, int, str]], object: Object) -> None: self.name = name self.hometown = hometown self.list = list self.object = object 4 sẽ được sử dụng thay vì # Generated by //quicktype.io # # To change quicktype's target language, run command: # # "Set quicktype target language" from typing import List, Union class Hometown: name: str id: int def __init__(self, name: str, id: int) -> None: self.name = name self.id = id class Key: key: int def __init__(self, key: int) -> None: self.key = key class Object: key: Key def __init__(self, key: Key) -> None: self.key = key class FbData: name: str hometown: Hometown list: List[Union[Key, int, str]] object: Object def __init__(self, name: str, hometown: Hometown, list: List[Union[Key, int, str]], object: Object) -> None: self.name = name self.hometown = hometown self.list = list self.object = object 3. Sử dụng tính năng này, chúng tôi có thể triển khai bộ giải mã tùy chỉnh.# Generated by //quicktype.io # # To change quicktype's target language, run command: # # "Set quicktype target language" from typing import List, Union class Hometown: name: str id: int def __init__(self, name: str, id: int) -> None: self.name = name self.id = id class Key: key: int def __init__(self, key: int) -> None: self.key = key class Object: key: Key def __init__(self, key: Key) -> None: self.key = key class FbData: name: str hometown: Hometown list: List[Union[Key, int, str]] object: Object def __init__(self, name: str, hometown: Hometown, list: List[Union[Key, int, str]], object: Object) -> None: self.name = name self.hometown = hometown self.list = list self.object = object 4parameter of the # Generated by //quicktype.io # # To change quicktype's target language, run command: # # "Set quicktype target language" from typing import List, Union class Hometown: name: str id: int def __init__(self, name: str, id: int) -> None: self.name = name self.id = id class Key: key: int def __init__(self, key: int) -> None: self.key = key class Object: key: Key def __init__(self, key: Key) -> None: self.key = key class FbData: name: str hometown: Hometown list: List[Union[Key, int, str]] object: Object def __init__(self, name: str, hometown: Hometown, list: List[Union[Key, int, str]], object: Object) -> None: self.name = name self.hometown = hometown self.list = list self.object = object 5 and # Generated by //quicktype.io # # To change quicktype's target language, run command: # # "Set quicktype target language" from typing import List, Union class Hometown: name: str id: int def __init__(self, name: str, id: int) -> None: self.name = name self.id = id class Key: key: int def __init__(self, key: int) -> None: self.key = key class Object: key: Key def __init__(self, key: Key) -> None: self.key = key class FbData: name: str hometown: Hometown list: List[Union[Key, int, str]] object: Object def __init__(self, name: str, hometown: Hometown, list: List[Union[Key, int, str]], object: Object) -> None: self.name = name self.hometown = hometown self.list = list self.object = object 6 method. The # Generated by //quicktype.io # # To change quicktype's target language, run command: # # "Set quicktype target language" from typing import List, Union class Hometown: name: str id: int def __init__(self, name: str, id: int) -> None: self.name = name self.id = id class Key: key: int def __init__(self, key: int) -> None: self.key = key class Object: key: Key def __init__(self, key: Key) -> None: self.key = key class FbData: name: str hometown: Hometown list: List[Union[Key, int, str]] object: Object def __init__(self, name: str, hometown: Hometown, list: List[Union[Key, int, str]], object: Object) -> None: self.name = name self.hometown = hometown self.list = list self.object = object 4 is an optional function that will be called with the result of any object literal decoded (a dict). So when we execute # Generated by //quicktype.io # # To change quicktype's target language, run command: # # "Set quicktype target language" from typing import List, Union class Hometown: name: str id: int def __init__(self, name: str, id: int) -> None: self.name = name self.id = id class Key: key: int def __init__(self, key: int) -> None: self.key = key class Object: key: Key def __init__(self, key: Key) -> None: self.key = key class FbData: name: str hometown: Hometown list: List[Union[Key, int, str]] object: Object def __init__(self, name: str, hometown: Hometown, list: List[Union[Key, int, str]], object: Object) -> None: self.name = name self.hometown = hometown self.list = list self.object = object 5, The return value of # Generated by //quicktype.io # # To change quicktype's target language, run command: # # "Set quicktype target language" from typing import List, Union class Hometown: name: str id: int def __init__(self, name: str, id: int) -> None: self.name = name self.id = id class Key: key: int def __init__(self, key: int) -> None: self.key = key class Object: key: Key def __init__(self, key: Key) -> None: self.key = key class FbData: name: str hometown: Hometown list: List[Union[Key, int, str]] object: Object def __init__(self, name: str, hometown: Hometown, list: List[Union[Key, int, str]], object: Object) -> None: self.name = name self.hometown = hometown self.list = list self.object = object 4 will be used instead of the # Generated by //quicktype.io # # To change quicktype's target language, run command: # # "Set quicktype target language" from typing import List, Union class Hometown: name: str id: int def __init__(self, name: str, id: int) -> None: self.name = name self.id = id class Key: key: int def __init__(self, key: int) -> None: self.key = key class Object: key: Key def __init__(self, key: Key) -> None: self.key = key class FbData: name: str hometown: Hometown list: List[Union[Key, int, str]] object: Object def __init__(self, name: str, hometown: Hometown, list: List[Union[Key, int, str]], object: Object) -> None: self.name = name self.hometown = hometown self.list = list self.object = object 3. Using this feature, we can implement custom decoders.
Để chuyển đổi JSON thành loại Python tùy chỉnh, chúng ta cần làm theo những điều sau đây:
Như chúng ta đã biết phương thức # Generated by //quicktype.io # # To change quicktype's target language, run command: # # "Set quicktype target language" from typing import List, Union class Hometown: name: str id: int def __init__(self, name: str, id: int) -> None: self.name = name self.id = id class Key: key: int def __init__(self, key: int) -> None: self.key = key class Object: key: Key def __init__(self, key: Key) -> None: self.key = key class FbData: name: str hometown: Hometown list: List[Union[Key, int, str]] object: Object def __init__(self, name: str, hometown: Hometown, list: List[Union[Key, int, str]], object: Object) -> None: self.name = name self.hometown = hometown self.list = list self.object = object 6 và # Generated by //quicktype.io # # To change quicktype's target language, run command: # # "Set quicktype target language" from typing import List, Union class Hometown: name: str id: int def __init__(self, name: str, id: int) -> None: self.name = name self.id = id class Key: key: int def __init__(self, key: int) -> None: self.key = key class Object: key: Key def __init__(self, key: Key) -> None: self.key = key class FbData: name: str hometown: Hometown list: List[Union[Key, int, str]] object: Object def __init__(self, name: str, hometown: Hometown, list: List[Union[Key, int, str]], object: Object) -> None: self.name = name self.hometown = hometown self.list = list self.object = object 5 Chuyển đổi JSON thành đối tượng # Generated by //quicktype.io # # To change quicktype's target language, run command: # # "Set quicktype target language" from typing import List, Union class Hometown: name: str id: int def __init__(self, name: str, id: int) -> None: self.name = name self.id = id class Key: key: int def __init__(self, key: int) -> None: self.key = key class Object: key: Key def __init__(self, key: Key) -> None: self.key = key class FbData: name: str hometown: Hometown list: List[Union[Key, int, str]] object: Object def __init__(self, name: str, hometown: Hometown, list: List[Union[Key, int, str]], object: Object) -> None: self.name = name self.hometown = hometown self.list = list self.object = object 3 để chúng ta cần tạo một chức năng tùy chỉnh nơi chúng ta có thể chuyển đổi # Generated by //quicktype.io # # To change quicktype's target language, run command: # # "Set quicktype target language" from typing import List, Union class Hometown: name: str id: int def __init__(self, name: str, id: int) -> None: self.name = name self.id = id class Key: key: int def __init__(self, key: int) -> None: self.key = key class Object: key: Key def __init__(self, key: Key) -> None: self.key = key class FbData: name: str hometown: Hometown list: List[Union[Key, int, str]] object: Object def __init__(self, name: str, hometown: Hometown, list: List[Union[Key, int, str]], object: Object) -> None: self.name = name self.hometown = hometown self.list = list self.object = object 3 thành loại Python tùy chỉnh. và chuyển hàm mới được tạo này cho tham số # Generated by //quicktype.io # # To change quicktype's target language, run command: # # "Set quicktype target language" from typing import List, Union class Hometown: name: str id: int def __init__(self, name: str, id: int) -> None: self.name = name self.id = id class Key: key: int def __init__(self, key: int) -> None: self.key = key class Object: key: Key def __init__(self, key: Key) -> None: self.key = key class FbData: name: str hometown: Hometown list: List[Union[Key, int, str]] object: Object def __init__(self, name: str, hometown: Hometown, list: List[Union[Key, int, str]], object: Object) -> None: self.name = name self.hometown = hometown self.list = list self.object = object 4 của phương thức import json from collections import namedtuple from json import JSONEncoder def customStudentDecoder(studentDict): return namedtuple('X', studentDict.keys())(*studentDict.values()) #Assume you received this JSON response studentJsonData = '{"rollNumber": 1, "name": "Emma"}' # Parse JSON into an object with attributes corresponding to dict keys. student = json.loads(studentJsonData, object_hook=customStudentDecoder) print("After Converting JSON Data into Custom Python Object") print(student.rollNumber, student.name)6. Vì vậy, chúng tôi có thể nhận được loại tùy chỉnh tại thời điểm giải mã JSON.create a custom function where we can convert # Generated by //quicktype.io # # To change quicktype's target language, run command: # # "Set quicktype target language" from typing import List, Union class Hometown: name: str id: int def __init__(self, name: str, id: int) -> None: self.name = name self.id = id class Key: key: int def __init__(self, key: int) -> None: self.key = key class Object: key: Key def __init__(self, key: Key) -> None: self.key = key class FbData: name: str hometown: Hometown list: List[Union[Key, int, str]] object: Object def __init__(self, name: str, hometown: Hometown, list: List[Union[Key, int, str]], object: Object) -> None: self.name = name self.hometown = hometown self.list = list self.object = object 3 into a custom Python type. and pass this newly created function to an # Generated by //quicktype.io # # To change quicktype's target language, run command: # # "Set quicktype target language" from typing import List, Union class Hometown: name: str id: int def __init__(self, name: str, id: int) -> None: self.name = name self.id = id class Key: key: int def __init__(self, key: int) -> None: self.key = key class Object: key: Key def __init__(self, key: Key) -> None: self.key = key class FbData: name: str hometown: Hometown list: List[Union[Key, int, str]] object: Object def __init__(self, name: str, hometown: Hometown, list: List[Union[Key, int, str]], object: Object) -> None: self.name = name self.hometown = hometown self.list = list self.object = object 4 parameter of a import json from collections import namedtuple from json import JSONEncoder def customStudentDecoder(studentDict): return namedtuple('X', studentDict.keys())(*studentDict.values()) #Assume you received this JSON response studentJsonData = '{"rollNumber": 1, "name": "Emma"}' # Parse JSON into an object with attributes corresponding to dict keys. student = json.loads(studentJsonData, object_hook=customStudentDecoder) print("After Converting JSON Data into Custom Python Object") print(student.rollNumber, student.name)6 method. so we can get custom type at the time of decoding JSON.
Tên được đặt tên là lớp, theo mô -đun bộ sưu tập. Giống như các đối tượng loại từ điển, nó chứa các khóa và được ánh xạ tới một số giá trị. Trong trường hợp này, chúng ta có thể truy cập các yếu tố bằng các khóa và chỉ mục.namedtuple is class, under the collections module. Like the dictionary type objects, it contains keys and that are mapped to some values. In this case, we can access the elements using keys and indexes.
Trước tiên, hãy để xem ví dụ đơn giản sau đó chúng ta có thể chuyển sang ví dụ thực tế. Trong ví dụ này, chúng tôi đang chuyển đổi dữ liệu JSON của sinh viên thành loại lớp học sinh tùy chỉnh.
import json from collections import namedtuple from json import JSONEncoder def customStudentDecoder(studentDict): return namedtuple('X', studentDict.keys())(*studentDict.values()) #Assume you received this JSON response studentJsonData = '{"rollNumber": 1, "name": "Emma"}' # Parse JSON into an object with attributes corresponding to dict keys. student = json.loads(studentJsonData, object_hook=customStudentDecoder) print("After Converting JSON Data into Custom Python Object") print(student.rollNumber, student.name)Output::
After Converting JSON Data into Custom Python Object 1 EmmaNhư bạn có thể thấy, chúng tôi đã chuyển đổi dữ liệu JSON có mặt ở định dạng chuỗi JSON thành một sinh viên đối tượng Python tùy chỉnh. Bây giờ, chúng ta có thể truy cập các thành viên của mình bằng toán tử DOT (.).
Bây giờ, hãy để Lừa xem kịch bản thời gian thực nơi làm việc với các đối tượng Python phức tạp. Và chúng ta cần chuyển đổi đối tượng Python tùy chỉnh thành JSON. Ngoài ra, chúng tôi muốn xây dựng một đối tượng Python tùy chỉnh từ JSON.convert custom Python object into JSON. Also, we want to construct a custom Python object from JSON.
Trong ví dụ này, chúng tôi đang sử dụng hai lớp import json from collections import namedtuple from json import JSONEncoder def customStudentDecoder(studentDict): return namedtuple('X', studentDict.keys())(*studentDict.values()) #Assume you received this JSON response studentJsonData = '{"rollNumber": 1, "name": "Emma"}' # Parse JSON into an object with attributes corresponding to dict keys. student = json.loads(studentJsonData, object_hook=customStudentDecoder) print("After Converting JSON Data into Custom Python Object") print(student.rollNumber, student.name)7 và ________ 48. & nbsp; Một lớp import json from collections import namedtuple from json import JSONEncoder def customStudentDecoder(studentDict): return namedtuple('X', studentDict.keys())(*studentDict.values()) #Assume you received this JSON response studentJsonData = '{"rollNumber": 1, "name": "Emma"}' # Parse JSON into an object with attributes corresponding to dict keys. student = json.loads(studentJsonData, object_hook=customStudentDecoder) print("After Converting JSON Data into Custom Python Object") print(student.rollNumber, student.name)8 là một thành viên của lớp import json from collections import namedtuple from json import JSONEncoder def customStudentDecoder(studentDict): return namedtuple('X', studentDict.keys())(*studentDict.values()) #Assume you received this JSON response studentJsonData = '{"rollNumber": 1, "name": "Emma"}' # Parse JSON into an object with attributes corresponding to dict keys. student = json.loads(studentJsonData, object_hook=customStudentDecoder) print("After Converting JSON Data into Custom Python Object") print(student.rollNumber, student.name)7.
- Đầu tiên, chúng tôi mã hóa lớp học sinh thành dữ liệu JSON.
- Sau đó, chúng tôi sử dụng cùng một dữ liệu JSON để giải mã nó thành một lớp học sinh
Hãy để xem ví dụ bây giờ.
import json from collections import namedtuple from json import JSONEncoder class Student: def __init__(self, rollNumber, name, marks): self.rollNumber, self.name, self.marks = rollNumber, name, marks class Marks: def __init__(self, english, geometry): self.english, self.geometry = english, geometry class StudentEncoder(JSONEncoder): def default(self, o): return o.__dict__ def customStudentDecoder(studentDict): return namedtuple('X', studentDict.keys())(*studentDict.values()) marks = Marks(82, 74) student = Student(1, "Emma", marks) # dumps() produces JSON in native str format. if you want to writ it in file use dump() studentJson = json.dumps(student, indent=4, cls=StudentEncoder) print("Student JSON") print(studentJson) # Parse JSON into an object with attributes corresponding to dict keys. studObj = json.loads(studentJson, object_hook=customStudentDecoder) print("After Converting JSON Data into Custom Python Object") print(studObj.rollNumber, studObj.name, studObj.marks.english, studObj.marks.geometry)Output::
Student JSON { "rollNumber": 1, "name": "Emma", "marks": { "english": 82, "geometry": 74 } } After Converting JSON Data into Custom Python Object 1 Emma 82 74Sử dụng các loại.simplenamespace và object_hook & nbsp; Để chuyển đổi dữ liệu JSON thành một đối tượng Python tùy chỉnh
Chúng ta có thể sử dụng After Converting JSON Data into Custom Python Object 1 Emma1 làm container cho các đối tượng JSON. Nó cung cấp những lợi thế sau hơn một giải pháp được đặt tên: -
- Thời gian thực hiện của nó ít hơn vì nó không tạo ra một lớp cho mỗi đối tượng.
- Nó chính xác và đơn giản
Trong ví dụ này, chúng tôi sẽ sử dụng After Converting JSON Data into Custom Python Object 1 Emma1 và # Generated by //quicktype.io # # To change quicktype's target language, run command: # # "Set quicktype target language" from typing import List, Union class Hometown: name: str id: int def __init__(self, name: str, id: int) -> None: self.name = name self.id = id class Key: key: int def __init__(self, key: int) -> None: self.key = key class Object: key: Key def __init__(self, key: Key) -> None: self.key = key class FbData: name: str hometown: Hometown list: List[Union[Key, int, str]] object: Object def __init__(self, name: str, hometown: Hometown, list: List[Union[Key, int, str]], object: Object) -> None: self.name = name self.hometown = hometown self.list = list self.object = object 4 để chuyển đổi dữ liệu JSON thành đối tượng Python tùy chỉnh.
from __future__ import print_function import json from json import JSONEncoder try: from types import SimpleNamespace as Namespace except ImportError: # Python 2.x fallback from argparse import Namespace class Student: def __init__(self, rollNumber, name, marks): self.rollNumber, self.name, self.marks = rollNumber, name, marks class Marks: def __init__(self, english, geometry): self.english, self.geometry = english, geometry class StudentEncoder(JSONEncoder): def default(self, o): return o.__dict__ marks = Marks(82, 74) student = Student(1, "Emma", marks) # dumps() produces JSON in native str format. if you want to writ it in file use dump() studentJsonData = json.dumps(student, indent=4, cls=StudentEncoder) print("Student JSON") print(studentJsonData) # Parse JSON into an custom Student object. studObj = json.loads(studentJsonData, object_hook=lambda d: Namespace(**d)) print("After Converting JSON Data into Custom Python Object using SimpleNamespace") print(studObj.rollNumber, studObj.name, studObj.marks.english, studObj.marks.geometry)Output::
Student JSON { "rollNumber": 1, "name": "Emma", "marks": { "english": 82, "geometry": 74 } } After Converting JSON Data into Custom Python Object using SimpleNamespace 1 Emma 82 74Sử dụng giải mã đối tượng của lớp JSondecoder để chuyển đổi dữ liệu JSON thành đối tượng Python tùy chỉnh
Chúng ta có thể sử dụng lớp After Converting JSON Data into Custom Python Object 1 Emma4 của mô -đun JSON để giải mã đối tượng JSON, ở đây chúng ta có thể giải mã một đối tượng JSON thành loại Python tùy chỉnh.
Chúng ta cần tạo một chức năng mới trong một lớp sẽ chịu trách nhiệm kiểm tra loại đối tượng trong chuỗi JSON, sau khi nhận được loại chính xác trong dữ liệu JSON, chúng ta có thể xây dựng đối tượng của mình.
Hãy để xem ví dụ.
import json class AppConfiguration(object): def __init__(self, data=None): if data is None: with open("fb_data.json") as fh: data = json.loads(fh.read()) else: data = dict(data) for key, val in data.items(): setattr(self, key, self.compute_attr_value(val)) def compute_attr_value(self, value): if isinstance(value, list): return [self.compute_attr_value(x) for x in value] elif isinstance(value, dict): return AppConfiguration(value) else: return value if __name__ == "__main__": instance = AppConfiguration() print(instance.name) print(instance.hometown.name) print(instance.hometown.id) print(instance.list[4].key) print(instance.object.key.key) 0Output::
import json class AppConfiguration(object): def __init__(self, data=None): if data is None: with open("fb_data.json") as fh: data = json.loads(fh.read()) else: data = dict(data) for key, val in data.items(): setattr(self, key, self.compute_attr_value(val)) def compute_attr_value(self, value): if isinstance(value, list): return [self.compute_attr_value(x) for x in value] elif isinstance(value, dict): return AppConfiguration(value) else: return value if __name__ == "__main__": instance = AppConfiguration() print(instance.name) print(instance.hometown.name) print(instance.hometown.id) print(instance.list[4].key) print(instance.object.key.key) 1Sử dụng mô -đun JsonPickle để chuyển đổi dữ liệu JSON thành đối tượng Python tùy chỉnh
JsonPickle là một thư viện Python được thiết kế để hoạt động với các đối tượng Python phức tạp. Bạn có thể sử dụng JsonPickle để tuần tự hóa và dữ liệu Python và JSON của Neserialization. Bạn có thể tham khảo tài liệu JsonPickle để biết thêm chi tiết.
Mô-đun JSON tích hợp của Python chỉ có thể xử lý các nguyên thủy Python. Đối với bất kỳ đối tượng Python tùy chỉnh nào, chúng ta cần viết jsonencoder và bộ giải mã của riêng mình.
Sử dụng jsonpickle, chúng tôi sẽ làm như sau: -
- Đầu tiên, chúng tôi sẽ mã hóa đối tượng sinh viên thành JSON bằng JsonPickle
- Sau đó, chúng tôi sẽ giải mã sinh viên JSON thành đối tượng học sinh
Bây giờ, hãy để Lừa xem ví dụ JsonPickle để chuyển đổi dữ liệu JSON thành một đối tượng Python tùy chỉnh.
import json class AppConfiguration(object): def __init__(self, data=None): if data is None: with open("fb_data.json") as fh: data = json.loads(fh.read()) else: data = dict(data) for key, val in data.items(): setattr(self, key, self.compute_attr_value(val)) def compute_attr_value(self, value): if isinstance(value, list): return [self.compute_attr_value(x) for x in value] elif isinstance(value, dict): return AppConfiguration(value) else: return value if __name__ == "__main__": instance = AppConfiguration() print(instance.name) print(instance.hometown.name) print(instance.hometown.id) print(instance.list[4].key) print(instance.object.key.key) 2Output:
import json class AppConfiguration(object): def __init__(self, data=None): if data is None: with open("fb_data.json") as fh: data = json.loads(fh.read()) else: data = dict(data) for key, val in data.items(): setattr(self, key, self.compute_attr_value(val)) def compute_attr_value(self, value): if isinstance(value, list): return [self.compute_attr_value(x) for x in value] elif isinstance(value, dict): return AppConfiguration(value) else: return value if __name__ == "__main__": instance = AppConfiguration() print(instance.name) print(instance.hometown.name) print(instance.hometown.id) print(instance.list[4].key) print(instance.object.key.key) 3Tạo một đối tượng mới và chuyển từ điển kết quả dưới dạng bản đồ để chuyển đổi dữ liệu JSON thành đối tượng Python tùy chỉnh
Như chúng ta đã biết phương thức # Generated by //quicktype.io # # To change quicktype's target language, run command: # # "Set quicktype target language" from typing import List, Union class Hometown: name: str id: int def __init__(self, name: str, id: int) -> None: self.name = name self.id = id class Key: key: int def __init__(self, key: int) -> None: self.key = key class Object: key: Key def __init__(self, key: Key) -> None: self.key = key class FbData: name: str hometown: Hometown list: List[Union[Key, int, str]] object: Object def __init__(self, name: str, hometown: Hometown, list: List[Union[Key, int, str]], object: Object) -> None: self.name = name self.hometown = hometown self.list = list self.object = object 5 và # Generated by //quicktype.io # # To change quicktype's target language, run command: # # "Set quicktype target language" from typing import List, Union class Hometown: name: str id: int def __init__(self, name: str, id: int) -> None: self.name = name self.id = id class Key: key: int def __init__(self, key: int) -> None: self.key = key class Object: key: Key def __init__(self, key: Key) -> None: self.key = key class FbData: name: str hometown: Hometown list: List[Union[Key, int, str]] object: Object def __init__(self, name: str, hometown: Hometown, list: List[Union[Key, int, str]], object: Object) -> None: self.name = name self.hometown = hometown self.list = list self.object = object 6 trả về một đối tượng # Generated by //quicktype.io # # To change quicktype's target language, run command: # # "Set quicktype target language" from typing import List, Union class Hometown: name: str id: int def __init__(self, name: str, id: int) -> None: self.name = name self.id = id class Key: key: int def __init__(self, key: int) -> None: self.key = key class Object: key: Key def __init__(self, key: Key) -> None: self.key = key class FbData: name: str hometown: Hometown list: List[Union[Key, int, str]] object: Object def __init__(self, name: str, hometown: Hometown, list: List[Union[Key, int, str]], object: Object) -> None: self.name = name self.hometown = hometown self.list = list self.object = object 3. Chúng ta có thể xây dựng một đối tượng tùy chỉnh mới bằng cách chuyển đối tượng # Generated by //quicktype.io # # To change quicktype's target language, run command: # # "Set quicktype target language" from typing import List, Union class Hometown: name: str id: int def __init__(self, name: str, id: int) -> None: self.name = name self.id = id class Key: key: int def __init__(self, key: int) -> None: self.key = key class Object: key: Key def __init__(self, key: Key) -> None: self.key = key class FbData: name: str hometown: Hometown list: List[Union[Key, int, str]] object: Object def __init__(self, name: str, hometown: Hometown, list: List[Union[Key, int, str]], object: Object) -> None: self.name = name self.hometown = hometown self.list = list self.object = object 3 dưới dạng tham số cho hàm tạo đối tượng sinh viên. tức là, chúng ta có thể ánh xạ đối tượng # Generated by //quicktype.io # # To change quicktype's target language, run command: # # "Set quicktype target language" from typing import List, Union class Hometown: name: str id: int def __init__(self, name: str, id: int) -> None: self.name = name self.id = id class Key: key: int def __init__(self, key: int) -> None: self.key = key class Object: key: Key def __init__(self, key: Key) -> None: self.key = key class FbData: name: str hometown: Hometown list: List[Union[Key, int, str]] object: Object def __init__(self, name: str, hometown: Hometown, list: List[Union[Key, int, str]], object: Object) -> None: self.name = name self.hometown = hometown self.list = list self.object = object 3 đến một đối tượng tùy chỉnh.
import json class AppConfiguration(object): def __init__(self, data=None): if data is None: with open("fb_data.json") as fh: data = json.loads(fh.read()) else: data = dict(data) for key, val in data.items(): setattr(self, key, self.compute_attr_value(val)) def compute_attr_value(self, value): if isinstance(value, list): return [self.compute_attr_value(x) for x in value] elif isinstance(value, dict): return AppConfiguration(value) else: return value if __name__ == "__main__": instance = AppConfiguration() print(instance.name) print(instance.hometown.name) print(instance.hometown.id) print(instance.list[4].key) print(instance.object.key.key) 4Đầu ra
import json class AppConfiguration(object): def __init__(self, data=None): if data is None: with open("fb_data.json") as fh: data = json.loads(fh.read()) else: data = dict(data) for key, val in data.items(): setattr(self, key, self.compute_attr_value(val)) def compute_attr_value(self, value): if isinstance(value, list): return [self.compute_attr_value(x) for x in value] elif isinstance(value, dict): return AppConfiguration(value) else: return value if __name__ == "__main__": instance = AppConfiguration() print(instance.name) print(instance.hometown.name) print(instance.hometown.id) print(instance.list[4].key) print(instance.object.key.key) 5Vậy bạn nghĩ như thế nào?
Tôi muốn nghe từ bạn. Bạn nghĩ gì về bài viết này? Hoặc có thể tôi đã bỏ lỡ một trong những cách để chuyển đổi dữ liệu JSON thành một đối tượng Python tùy chỉnh. Dù bằng cách nào, hãy cho tôi biết bằng cách để lại một bình luận dưới đây.leaving a comment below.
Ngoài ra, hãy cố gắng giải bài tập Python JSON để hiểu rõ hơn về việc làm việc với dữ liệu JSON trong Python.