Vì vậy, tôi có một số python mà tôi muốn tuần tự hóa thành json
{'someproperty': 0, 'anotherproperty': 'value', 'propertyobject': SomeObject[someproperty=0, anotherproperty=0]}
Nhưng json.dumps
ném một TypeError: SomeObject[someproperty=0, anotherproperty=0] is not JSON serializable
Vậy làm thế nào tôi có thể tuần tự hóa Python của tôi một cách đúng đắn?
Hỏi ngày 27 tháng 4 năm 2016 lúc 4:02Apr 27, 2016 at 4:02
1
Vấn đề là, Python không biết cách đại diện cho SomeObject
Bạn có thể tạo một dự phòng như vậy:
import json
def dumper[obj]:
try:
return obj.toJSON[]
except:
return obj.__dict__
obj = {'someproperty': 0, 'anotherproperty': 'value', 'propertyobject': SomeObject[someproperty=0, anotherproperty=0]}
print json.dumps[obj, default=dumper, indent=2]
Đã trả lời ngày 27 tháng 4 năm 2016 lúc 4:15Apr 27, 2016 at 4:15
Mate Hegedusmate HegedusMate Hegedus
2.8471 Huy hiệu vàng19 Huy hiệu bạc29 Huy hiệu đồng1 gold badge19 silver badges29 bronze badges
2
Python chỉ có thể tuần tự hóa các đối tượng được tích hợp trong kiểu dữ liệu. Trong trường hợp của bạn, "Somebject" là loại do người dùng xác định mà Python không thể tuần tự hóa. Nếu bạn cố gắng tuần tự hóa bất kỳ loại dữ liệu nào không thể nối tiếp với JSON, bạn sẽ nhận được một kiểu chữ "Kiểu mẫu: không phải là JSON serializable". Vì vậy, cần có một bước trung gian chuyển đổi các loại dữ liệu không được tích hợp này thành python được xây dựng trong cấu trúc dữ liệu có thể nối tiếp [danh sách, dict, số và chuỗi]. In your case, "SomeObject" is a User defined type that Python cannot serialize. If you try to serialize any data type which is not json serializable, you get a TypeError "TypeError: is not JSON serializable". So there should be an intermediate step that converts these non built in data types into Python built in serializable data structure [list, dict, number and string].
Vì vậy, hãy để chúng tôi chuyển đổi một số đối tượng của bạn thành một từ điển Python, vì từ điển là cách dễ nhất để thể hiện đối tượng của bạn [vì nó có các cặp khóa/giá trị]. Bạn chỉ có thể sao chép tất cả các thuộc tính phiên bản nào đó của bạn vào một từ điển mới và bạn đã được thiết lập! mydict = self .__ dict __. Sao chép [] MyDict này giờ đây có thể là giá trị của "propertyObject" của bạn.myDict = self.__dict__.copy[] This myDict can now be the value of your "propertyobject".
Sau bước này là khi bạn chuyển đổi từ điển thành một chuỗi [định dạng JSON, nhưng nó có thể là yaml, xml, csv ...] - Đối với chúng tôi, đó sẽ là jsonobj = json.dumps [FinalDict]jsonObj = JSON.dumps[finalDict]
Bước cuối cùng là viết chuỗi jsonObj vào một tệp trên đĩa!
Đã trả lời ngày 27 tháng 6 năm 2017 lúc 19:07Jun 27, 2017 at 19:07
Meghameghamegha
671 Huy hiệu bạc5 Huy hiệu đồng1 silver badge5 bronze badges
Đối tượng của loại dict_values không phải là json serializable #
Python "TypeError: Đối tượng của loại dict_values không phải là JSON serializable" xảy ra khi chúng ta cố gắng chuyển đổi đối tượng
0 thành JSON. Để giải quyết lỗi, hãy chuyển đối tượng import json
def dumper[obj]:
try:
return obj.toJSON[]
except:
return obj.__dict__
obj = {'someproperty': 0, 'anotherproperty': 'value', 'propertyobject': SomeObject[someproperty=0, anotherproperty=0]}
print json.dumps[obj, default=dumper, indent=2]
0 cho lớp import json
def dumper[obj]:
try:
return obj.toJSON[]
except:
return obj.__dict__
obj = {'someproperty': 0, 'anotherproperty': 'value', 'propertyobject': SomeObject[someproperty=0, anotherproperty=0]}
print json.dumps[obj, default=dumper, indent=2]
2 trước khi chuyển đổi sang JSON.import json
def dumper[obj]:
try:
return obj.toJSON[]
except:
return obj.__dict__
obj = {'someproperty': 0, 'anotherproperty': 'value', 'propertyobject': SomeObject[someproperty=0, anotherproperty=0]}
print json.dumps[obj, default=dumper, indent=2]
Từ điển có phải là python có thể nối tiếp không?
Copied!
import json my_dict = {'name': 'Alice', 'age': 30} # ⛔️ TypeError: Object of type dict_values is not JSON serializable json_str = json.dumps[my_dict.values[]]
Trong Python, có nhiều định dạng khác nhau để tuần tự hóa có sẵn. Một ví dụ phổ biến về bản đồ băm [từ điển Python] hoạt động trên nhiều ngôn ngữ là định dạng tệp JSON có thể đọc được của con người và cho phép chúng tôi lưu trữ từ điển và tạo lại nó với cùng một cấu trúc.
JSON có phải là python có thể serializable không?
Copied!
import json my_dict = {'name': 'Alice', 'age': 30} # ✅ convert list values to list json_str = json.dumps[list[my_dict.values[]]] print[json_str] # 👉️ '["Alice", 30]' print[type[json_str]] # 👉️ ''
Mô -đun JSON phơi bày hai phương pháp để tuần tự hóa các đối tượng Python thành định dạng JSON. dump [] sẽ viết dữ liệu python vào một đối tượng giống như tệp. Chúng tôi sử dụng điều này khi chúng tôi muốn tuần tự hóa dữ liệu Python của chúng tôi vào tệp JSON bên ngoài. Dumps [] sẽ viết dữ liệu Python vào một chuỗi ở định dạng JSON.
Những đối tượng nào là Python có thể serializable đối tượng?
Bộ mã hóa JSON được triển khai trong các phương thức Dump [] và Dumps [] chỉ có thể tuần tự hóa một vài loại đối tượng cơ bản. Đó là từ điển, danh sách, chuỗi, số nguyên, phao, booleans, và không có.
Phương thức Dict.values trả về một cái nhìn mới về các giá trị của từ điển.
Ngoài ra, bạn có thể mở rộng từ lớp
1 và xử lý các chuyển đổi theo phương thứcCopied!
import json my_dict = {'name': 'Alice', 'age': 30} # ⛔️ TypeError: Object of type dict_values is not JSON serializable json_str = json.dumps[my_dict.values[]]
2.Copied!
import json my_dict = {'name': 'Alice', 'age': 30} # ⛔️ TypeError: Object of type dict_values is not JSON serializable json_str = json.dumps[my_dict.values[]]
Copied!
import json from collections import abc class DictValuesEncoder[json.JSONEncoder]: def default[self, obj]: if isinstance[obj, abc.ValuesView]: return list[obj] return json.JSONEncoder.default[self, obj] my_dict = {'name': 'Alice', 'age': 30} json_str = json.dumps[my_dict.values[], cls=DictValuesEncoder] print[json_str] # 👉️ '["Alice", 30]' print[type[json_str]] # 👉️
Chúng tôi mở rộng từ lớp jsonencoder.
Lớp
1 hỗ trợ các đối tượng và loại sau theo mặc định.Copied!
import json my_dict = {'name': 'Alice', 'age': 30} # ⛔️ TypeError: Object of type dict_values is not JSON serializable json_str = json.dumps[my_dict.values[]]
DIGN | sự vật |
Danh sách, tuple | mảng |
str | sợi dây |
int, float, int và float có nguồn gốc từ | con số |
ĐÚNG VẬY | thật |
Sai | sai |
Không có | vô giá trị |
Lưu ý rằng lớp
1 không hỗ trợ chuyển đổiCopied!
import json my_dict = {'name': 'Alice', 'age': 30} # ⛔️ TypeError: Object of type dict_values is not JSON serializable json_str = json.dumps[my_dict.values[]]
import json
def dumper[obj]:
try:
return obj.toJSON[]
except:
return obj.__dict__
obj = {'someproperty': 0, 'anotherproperty': 'value', 'propertyobject': SomeObject[someproperty=0, anotherproperty=0]}
print json.dumps[obj, default=dumper, indent=2]
0 sang JSON theo mặc định.Chúng ta có thể xử lý việc này bằng cách mở rộng từ lớp và thực hiện phương thức
6 trả về một đối tượng có thể nối tiếp.Copied!
import json my_dict = {'name': 'Alice', 'age': 30} # ⛔️ TypeError: Object of type dict_values is not JSON serializable json_str = json.dumps[my_dict.values[]]
Copied!
import json from collections import abc class DictValuesEncoder[json.JSONEncoder]: def default[self, obj]: if isinstance[obj, abc.ValuesView]: return list[obj] return json.JSONEncoder.default[self, obj]
Nếu giá trị được truyền là đối tượng
import json
def dumper[obj]:
try:
return obj.toJSON[]
except:
return obj.__dict__
obj = {'someproperty': 0, 'anotherproperty': 'value', 'propertyobject': SomeObject[someproperty=0, anotherproperty=0]}
print json.dumps[obj, default=dumper, indent=2]
0, chúng tôi chuyển đổi nó thành import json
def dumper[obj]:
try:
return obj.toJSON[]
except:
return obj.__dict__
obj = {'someproperty': 0, 'anotherproperty': 'value', 'propertyobject': SomeObject[someproperty=0, anotherproperty=0]}
print json.dumps[obj, default=dumper, indent=2]
7 và trả về kết quả.Hàm isinstance trả về
9 nếu được truyền trong đối tượng là một thể hiện hoặc một lớp con của được truyền trong lớp.Copied!
import json my_dict = {'name': 'Alice', 'age': 30} # ⛔️ TypeError: Object of type dict_values is not JSON serializable json_str = json.dumps[my_dict.values[]]
Trong tất cả các trường hợp khác, chúng tôi cho phép phương pháp mặc định của lớp cơ sở thực hiện tuần tự hóa.
Để sử dụng tùy chỉnh
1, chỉ định nó với đối số từ khóaCopied!
import json my_dict = {'name': 'Alice', 'age': 30} # ⛔️ TypeError: Object of type dict_values is not JSON serializable json_str = json.dumps[my_dict.values[]]
1 trong cuộc gọi của bạn đến phương thứcCopied!
import json my_dict = {'name': 'Alice', 'age': 30} # ✅ convert list values to list json_str = json.dumps[list[my_dict.values[]]] print[json_str] # 👉️ '["Alice", 30]' print[type[json_str]] # 👉️ ''
import json
def dumper[obj]:
try:
return obj.toJSON[]
except:
return obj.__dict__
obj = {'someproperty': 0, 'anotherproperty': 'value', 'propertyobject': SomeObject[someproperty=0, anotherproperty=0]}
print json.dumps[obj, default=dumper, indent=2]
4.Copied!
import json from collections import abc class DictValuesEncoder[json.JSONEncoder]: def default[self, obj]: if isinstance[obj, abc.ValuesView]: return list[obj] return json.JSONEncoder.default[self, obj] my_dict = {'name': 'Alice', 'age': 30} # ✅ pass cls kwarg json_str = json.dumps[my_dict.values[], cls=DictValuesEncoder] print[json_str] # 👉️ '["Alice", 30]' print[type[json_str]] # 👉️
Nếu bạn không cung cấp
1 kwarg,Copied!
import json my_dict = {'name': 'Alice', 'age': 30} # ✅ convert list values to list json_str = json.dumps[list[my_dict.values[]]] print[json_str] # 👉️ '["Alice", 30]' print[type[json_str]] # 👉️ ''
1 mặc định được sử dụng.Copied!
import json my_dict = {'name': 'Alice', 'age': 30} # ⛔️ TypeError: Object of type dict_values is not JSON serializable json_str = json.dumps[my_dict.values[]]
Sự kết luận #
Python "TypeError: Đối tượng của loại dict_values không phải là JSON serializable" xảy ra khi chúng ta cố gắng chuyển đổi đối tượng
0 thành JSON. Để giải quyết lỗi, hãy chuyển đối tượng import json
def dumper[obj]:
try:
return obj.toJSON[]
except:
return obj.__dict__
obj = {'someproperty': 0, 'anotherproperty': 'value', 'propertyobject': SomeObject[someproperty=0, anotherproperty=0]}
print json.dumps[obj, default=dumper, indent=2]
0 cho lớp import json
def dumper[obj]:
try:
return obj.toJSON[]
except:
return obj.__dict__
obj = {'someproperty': 0, 'anotherproperty': 'value', 'propertyobject': SomeObject[someproperty=0, anotherproperty=0]}
print json.dumps[obj, default=dumper, indent=2]
2 trước khi chuyển đổi sang JSON.import json
def dumper[obj]:
try:
return obj.toJSON[]
except:
return obj.__dict__
obj = {'someproperty': 0, 'anotherproperty': 'value', 'propertyobject': SomeObject[someproperty=0, anotherproperty=0]}
print json.dumps[obj, default=dumper, indent=2]