Python protobuf转换为json

2024-07-03 06:21:51 发布

您现在位置:Python中文网/ 问答频道 /正文

我正在尝试转换消息对象

message = [id: "ff90608b-bb1f-463b-ad26-e0027e67e826"
byte_content: "PK\003\004\024\000\000\000\010\000\360\206\322R\007AMb\201\...00\000\310\031\000\000\000\000"
file_type: "application/pdf"
file_name: "cumulative-essentials-visit.pdf"
]

from google.protobuf.json_format import MessageToDict 
dict_obj = MessageToDict(message_obj)

发送到json,但出现错误

message_descriptor = message.DESCRIPTOR
AttributeError: 'google.protobuf.pyext._message.RepeatedCompositeCo' object has no attribute 'DESCRIPTOR'

有什么想法吗? 谢谢


Tags: 对象idjsonobj消息messagepdfgoogle
1条回答
网友
1楼 · 发布于 2024-07-03 06:21:51

下面是一个工作示例,同时重现了上述异常

步骤1:todolist.proto包含以下内容的文件:

syntax = "proto3";

// Not necessary for Python but should still be declared to avoid name collisions 
// in the Protocol Buffers namespace and non-Python languages
package protoblog;

// Style guide prefers prefixing enum values instead of surrounding
// with an enclosing message
enum TaskState {
    TASK_OPEN = 0;
    TASK_IN_PROGRESS = 1;
    TASK_POST_PONED = 2;
    TASK_CLOSED = 3;
    TASK_DONE = 4;
}

message TodoList {
    int32 owner_id = 1;
    string owner_name = 2;

    message ListItems {
        TaskState state = 1;
        string task = 2;
        string due_date = 3;
    }

    repeated ListItems todos = 3;
}

步骤2:通过运行以下命令,从todolist.proto文件生成特定于python的代码:

protoc -I=.  python_out=. todolist.proto

这将在当前目录中生成一个文件todolist_pb2.py

步骤3:创建一个python项目并将复制到dolist_pb2.py

步骤4:创建包含以下内容的python模块proto_test.py:

import json
from google.protobuf.json_format import Parse
from google.protobuf.json_format import MessageToDict
from todolist_pb2 import TodoList

todolist_json_message = {
    "ownerId": "1234",
    "ownerName": "Tim",
    "todos": [
        {
            "state": "TASK_DONE",
            "task": "Test ProtoBuf for Python",
            "dueDate": "31.10.2019"
        }
    ]
}


todolist_proto_message = Parse(json.dumps(todolist_json_message), TodoList())
print(todolist_proto_message)

# Successfully converts the message to dictionary
todolist_proto_message_dict = MessageToDict(todolist_proto_message)
print(todolist_proto_message_dict)

# If you try to convert a field from your message rather than entire message,
# you will get object has no attribute 'DESCRIPTOR exception'
# Examples:
# Eg.1: Produces AttributeError: 'google.protobuf.pyext._message.RepeatedCompositeCo' object has no attribute
# 'DESCRIPTOR.'
todos_as_dict = MessageToDict(todolist_proto_message.todos)

# Eg.2: Produces AttributeError: 'int' object has no attribute 'DESCRIPTOR'
owner_id_as_dict = MessageToDict(todolist_proto_message.owner_id)

步骤5:运行proto_test.py模块,您可以看到失败的行为和成功的行为

因此,您似乎不是在转换实际消息,而是在转换消息/响应中的列表类型字段。因此,请尝试转换整个消息,然后检索您感兴趣的字段

如果有帮助,请告诉我

注意:您需要确保在您的计算机中安装了protoc compiler,以便将proto文件编译为步骤2中提到的python特定代码。 安装说明如下所示: MacOS/Linux

Windows

相关问题 更多 >