Hướng dẫn is a dictionary json serializable python? - là một từ điển json serializable python?

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

Hướng dẫn is a dictionary json serializable python? - là một từ điển json serializable python?

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

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 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.

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

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())
1 và xử lý các chuyển đổi theo phương thức

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())
2.

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

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())
1 hỗ trợ các đối tượng và loại sau theo mặc định.

PythonJson
DIGNsự vật
Danh sách, tuplemảng
strsợi dây
int, float, int và float có nguồn gốc từcon số
ĐÚNG VẬYthật
Saisai
Không cóvô giá trị

Lưu ý rằng 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())
1 không hỗ trợ chuyển đổi
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

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())
6 trả về một đối tượng có thể nối tiếp.

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ề

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())
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.

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

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())
1, chỉ định nó với đối số từ khóa

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 trong cuộc gọi của bạn đến phương thức
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

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 kwarg,

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())
1 mặc định được sử dụng.

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

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 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.

Từ điển có phải là python có thể nối tiếp không?

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?

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.. dump() will write Python data to a file-like object. We use this when we want to serialize our Python data to an external JSON file. dumps() will write Python data to a string in JSON format.

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ó.dictionaries, lists, strings, integers, floats, Booleans, and None.

JSON có phải là từ điển từ điển không?

JSON (ký hiệu đối tượng JavaScript) là một trong những định dạng phổ biến nhất được sử dụng để truyền dữ liệu giữa các trang web và chương trình.Đó là một định dạng có thể đọc được của con người, nhưng được cấu trúc theo phong cách quen thuộc mà bạn sẽ nhận ra ... về cơ bản nó là sự pha trộn của từ điển và danh sách!it's essentially a mix of dictionaries and lists!