Hướng dẫn convert json to enum python - chuyển đổi json sang enum python

Nếu bạn muốn mã hóa một thành viên enum.Enum tùy ý cho JSON và sau đó giải mã nó dưới dạng cùng một thành viên enum (thay vì chỉ đơn giản là thuộc tính ____ của thành viên enum), bạn có thể làm như vậy bằng cách viết một lớp object_hook Đối số cho json.load() hoặc

>>> data = {
...     "action": "frobnicate",
...     "status": Status.success
... }
>>> text = json.dumps(data, cls=EnumEncoder)
>>> text
'{"status": {"__enum__": "Status.success"}, "action": "frobnicate"}'
>>> json.loads(text, object_hook=as_enum)
{'status': <Status.success: 0>, 'action': 'frobnicate'}
0:

PUBLIC_ENUMS = {
    'Status': Status,
    # ...
}

class EnumEncoder(json.JSONEncoder):
    def default(self, obj):
        if type(obj) in PUBLIC_ENUMS.values():
            return {"__enum__": str(obj)}
        return json.JSONEncoder.default(self, obj)

def as_enum(d):
    if "__enum__" in d:
        name, member = d["__enum__"].split(".")
        return getattr(PUBLIC_ENUMS[name], member)
    else:
        return d

Hàm

>>> data = {
...     "action": "frobnicate",
...     "status": Status.success
... }
>>> text = json.dumps(data, cls=EnumEncoder)
>>> text
'{"status": {"__enum__": "Status.success"}, "action": "frobnicate"}'
>>> json.loads(text, object_hook=as_enum)
{'status': <Status.success: 0>, 'action': 'frobnicate'}
1 dựa vào JSON đã được mã hóa bằng cách sử dụng
>>> data = {
...     "action": "frobnicate",
...     "status": Status.success
... }
>>> text = json.dumps(data, cls=EnumEncoder)
>>> text
'{"status": {"__enum__": "Status.success"}, "action": "frobnicate"}'
>>> json.loads(text, object_hook=as_enum)
{'status': <Status.success: 0>, 'action': 'frobnicate'}
2 hoặc một cái gì đó hoạt động giống hệt với nó.

Hạn chế đối với các thành viên của

>>> data = {
...     "action": "frobnicate",
...     "status": Status.success
... }
>>> text = json.dumps(data, cls=EnumEncoder)
>>> text
'{"status": {"__enum__": "Status.success"}, "action": "frobnicate"}'
>>> json.loads(text, object_hook=as_enum)
{'status': <Status.success: 0>, 'action': 'frobnicate'}
3 là cần thiết để tránh một văn bản được chế tạo độc hại đang được sử dụng, ví dụ, thủ thuật gọi mã để lưu thông tin cá nhân (ví dụ: khóa bí mật được sử dụng bởi ứng dụng) đến trường cơ sở dữ liệu không liên quan, từ đó có thể được được phơi bày (xem https://chat.stackoverflow.com/transcript/message/35999686#35999686).

Ví dụ sử dụng:

>>> data = {
...     "action": "frobnicate",
...     "status": Status.success
... }
>>> text = json.dumps(data, cls=EnumEncoder)
>>> text
'{"status": {"__enum__": "Status.success"}, "action": "frobnicate"}'
>>> json.loads(text, object_hook=as_enum)
{'status': <Status.success: 0>, 'action': 'frobnicate'}

Chuyển đổi một enum thành json trong python #

Để chuyển đổi một enum thành JSON, hãy mở rộng từ các lớp

>>> data = {
...     "action": "frobnicate",
...     "status": Status.success
... }
>>> text = json.dumps(data, cls=EnumEncoder)
>>> text
'{"status": {"__enum__": "Status.success"}, "action": "frobnicate"}'
>>> json.loads(text, object_hook=as_enum)
{'status': <Status.success: 0>, 'action': 'frobnicate'}
4 hoặc
>>> data = {
...     "action": "frobnicate",
...     "status": Status.success
... }
>>> text = json.dumps(data, cls=EnumEncoder)
>>> text
'{"status": {"__enum__": "Status.success"}, "action": "frobnicate"}'
>>> json.loads(text, object_hook=as_enum)
{'status': <Status.success: 0>, 'action': 'frobnicate'}
5 khi khai báo lớp liệt kê của bạn, ví dụ:
>>> data = {
...     "action": "frobnicate",
...     "status": Status.success
... }
>>> text = json.dumps(data, cls=EnumEncoder)
>>> text
'{"status": {"__enum__": "Status.success"}, "action": "frobnicate"}'
>>> json.loads(text, object_hook=as_enum)
{'status': <Status.success: 0>, 'action': 'frobnicate'}
6. Sau đó, bạn sẽ có thể tuần tự hóa các thành viên Enum thành JSON trực tiếp bằng cách sử dụng phương thức
>>> data = {
...     "action": "frobnicate",
...     "status": Status.success
... }
>>> text = json.dumps(data, cls=EnumEncoder)
>>> text
'{"status": {"__enum__": "Status.success"}, "action": "frobnicate"}'
>>> json.loads(text, object_hook=as_enum)
{'status': <Status.success: 0>, 'action': 'frobnicate'}
7.

Copied!

from enum import Enum import json # 👇️ subclass str class first, then Enum class Color(str, Enum): RED = 'stop' GREEN = 'go' YELLOW = 'get ready' my_json = json.dumps(Color.RED) print(my_json) # 👉️ "stop" my_str = json.loads(my_json) print(my_str) # 👉️ 'stop'

Lớp

>>> data = {
...     "action": "frobnicate",
...     "status": Status.success
... }
>>> text = json.dumps(data, cls=EnumEncoder)
>>> text
'{"status": {"__enum__": "Status.success"}, "action": "frobnicate"}'
>>> json.loads(text, object_hook=as_enum)
{'status': <Status.success: 0>, 'action': 'frobnicate'}
8 là một lớp con của cả
>>> data = {
...     "action": "frobnicate",
...     "status": Status.success
... }
>>> text = json.dumps(data, cls=EnumEncoder)
>>> text
'{"status": {"__enum__": "Status.success"}, "action": "frobnicate"}'
>>> json.loads(text, object_hook=as_enum)
{'status': <Status.success: 0>, 'action': 'frobnicate'}
9 và

Copied!

from enum import Enum import json # 👇️ subclass str class first, then Enum class Color(str, Enum): RED = 'stop' GREEN = 'go' YELLOW = 'get ready' my_json = json.dumps(Color.RED) print(my_json) # 👉️ "stop" my_str = json.loads(my_json) print(my_str) # 👉️ 'stop'
0.

Bạn có thể sử dụng lớp

>>> data = {
...     "action": "frobnicate",
...     "status": Status.success
... }
>>> text = json.dumps(data, cls=EnumEncoder)
>>> text
'{"status": {"__enum__": "Status.success"}, "action": "frobnicate"}'
>>> json.loads(text, object_hook=as_enum)
{'status': <Status.success: 0>, 'action': 'frobnicate'}
5 để tạo một enum với các hằng số cũng là các lớp con là
>>> data = {
...     "action": "frobnicate",
...     "status": Status.success
... }
>>> text = json.dumps(data, cls=EnumEncoder)
>>> text
'{"status": {"__enum__": "Status.success"}, "action": "frobnicate"}'
>>> json.loads(text, object_hook=as_enum)
{'status': <Status.success: 0>, 'action': 'frobnicate'}
5.

Copied!

from enum import Enum import json class Color(int, Enum): RED = 1 GREEN = 2 YELLOW = 3 my_json = json.dumps(Color.RED) print(my_json) # 👉️ "1" my_int = json.loads(my_json) print(my_int) # 👉️ 1

Điều này rất giống với việc sử dụng lớp Intenum từ mô -đun

Copied!

from enum import Enum import json # 👇️ subclass str class first, then Enum class Color(str, Enum): RED = 'stop' GREEN = 'go' YELLOW = 'get ready' my_json = json.dumps(Color.RED) print(my_json) # 👉️ "stop" my_str = json.loads(my_json) print(my_str) # 👉️ 'stop'
3.

Copied!

from enum import IntEnum import json class Color(IntEnum): RED = 1 GREEN = 2 YELLOW = 3 my_json = json.dumps(Color.RED) print(my_json) # 👉️ "1" my_int = json.loads(my_json) print(my_int) # 👉️ 1

Thay vì kéo dài từ

>>> data = {
...     "action": "frobnicate",
...     "status": Status.success
... }
>>> text = json.dumps(data, cls=EnumEncoder)
>>> text
'{"status": {"__enum__": "Status.success"}, "action": "frobnicate"}'
>>> json.loads(text, object_hook=as_enum)
{'status': <Status.success: 0>, 'action': 'frobnicate'}
5 và

Copied!

from enum import Enum import json # 👇️ subclass str class first, then Enum class Color(str, Enum): RED = 'stop' GREEN = 'go' YELLOW = 'get ready' my_json = json.dumps(Color.RED) print(my_json) # 👉️ "stop" my_str = json.loads(my_json) print(my_str) # 👉️ 'stop'
0, chúng tôi đã mở rộng từ lớp

Copied!

from enum import Enum import json # 👇️ subclass str class first, then Enum class Color(str, Enum): RED = 'stop' GREEN = 'go' YELLOW = 'get ready' my_json = json.dumps(Color.RED) print(my_json) # 👉️ "stop" my_str = json.loads(my_json) print(my_str) # 👉️ 'stop'
6 để đạt được kết quả tương tự.

Lưu ý rằng có một số quy tắc khi làm việc với các liệt kê có nguồn gốc:

  1. Khi phân lớp

    Copied!

    from enum import Enum import json # 👇️ subclass str class first, then Enum class Color(str, Enum): RED = 'stop' GREEN = 'go' YELLOW = 'get ready' my_json = json.dumps(Color.RED) print(my_json) # 👉️ "stop" my_str = json.loads(my_json) print(my_str) # 👉️ 'stop'
    0, chỉ định các loại hỗn hợp trước lớp

    Copied!

    from enum import Enum import json # 👇️ subclass str class first, then Enum class Color(str, Enum): RED = 'stop' GREEN = 'go' YELLOW = 'get ready' my_json = json.dumps(Color.RED) print(my_json) # 👉️ "stop" my_str = json.loads(my_json) print(my_str) # 👉️ 'stop'
    0.
  2. Mặc dù

    Copied!

    from enum import Enum import json # 👇️ subclass str class first, then Enum class Color(str, Enum): RED = 'stop' GREEN = 'go' YELLOW = 'get ready' my_json = json.dumps(Color.RED) print(my_json) # 👉️ "stop" my_str = json.loads(my_json) print(my_str) # 👉️ 'stop'
    0 có thể có các thành viên thuộc bất kỳ loại nào, một khi các loại bổ sung được trộn lẫn, tất cả các thành viên trong enum phải có giá trị của loại được chỉ định (ví dụ:
    >>> data = {
    ...     "action": "frobnicate",
    ...     "status": Status.success
    ... }
    >>> text = json.dumps(data, cls=EnumEncoder)
    >>> text
    '{"status": {"__enum__": "Status.success"}, "action": "frobnicate"}'
    >>> json.loads(text, object_hook=as_enum)
    {'status': <Status.success: 0>, 'action': 'frobnicate'}
    
    5).

Làm thế nào để tuần tự hóa Enum cho JSON trong Python?

Để chuyển đổi một enum thành JSON, hãy mở rộng từ các lớp STR hoặc INT khi khai báo lớp liệt kê của bạn, ví dụ:Màu lớp (str, enum):.Sau đó, bạn sẽ có thể tuần tự hóa các thành viên enum thành JSON trực tiếp bằng cách sử dụng phương thức json.dumps ().by using the json. dumps() method.

JSON có hỗ trợ enum không?

JSON không có loại enum.Hai cách mô hình hóa một enum sẽ là: một mảng, như bạn có hiện tại.Các giá trị mảng là các phần tử và các định danh phần tử sẽ được biểu diễn bằng các chỉ mục mảng của các giá trị.. The two ways of modeling an enum would be: An array, as you have currently. The array values are the elements, and the element identifiers would be represented by the array indexes of the values.

Giá trị Enum có thể là chuỗi Python không?

Liệt kê được tạo bằng cách sử dụng các lớp.Enums có tên và giá trị liên quan đến chúng.Thuộc tính của Enum: Enums có thể được hiển thị dưới dạng chuỗi hoặc repr.Enums can be displayed as string or repr.

Enum có thể có nhiều giá trị python không?

Enums không thể có nhiều giá trị cho mỗi tên..