You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

无对应Schema下将Protobuf Blob转为JSON,现有代码不支持嵌套求解决方案

无需Schema将Protobuf Blob转JSON的方法

方法1:改进protoc --decode_raw输出的解析代码

protoc --decode_raw命令可在无Schema的情况下解析Protobuf Blob并输出结构化文本,你的现有代码仅处理了扁平字段,未适配嵌套结构。可以通过递归解析带缩进的输出来构建嵌套字典,最终转成JSON。

改进后的Python代码示例:

import json

def parse_protoc_raw_output(lines):
    message_dict = {}
    current_dict = message_dict
    stack = []
    for line in lines:
        line = line.strip()
        if not line:
            continue
        # 处理嵌套结构开始
        if line.endswith("{"):
            field_num = line[:-1].strip()
            nested_dict = {}
            current_dict[field_num] = nested_dict
            stack.append(current_dict)
            current_dict = nested_dict
            continue
        # 处理嵌套结构结束
        if line == "}":
            if stack:
                current_dict = stack.pop()
            continue
        # 处理普通键值字段
        parts = line.split(": ", 1)
        field_num = parts[0]
        value = parts[1] if len(parts) > 1 else None
        # 自动转换数值类型
        if value is not None:
            if value.isdigit():
                value = int(value)
            elif "." in value and value.replace(".", "").isdigit():
                try:
                    value = float(value)
                except ValueError:
                    pass
        current_dict[field_num] = value
    return message_dict

# 解析protoc输出并转JSON
lines = result.stdout.split("\n")
parsed_dict = parse_protoc_raw_output(lines)
json_result = json.dumps(parsed_dict, indent=2)
print(json_result)

这段代码会识别protoc输出中的{}标记和缩进,递归构建嵌套字典,最终输出符合要求的JSON,字段名使用原始的Protobuf字段编号。

方法2:使用Protobuf Python库的UnknownFieldSet解析

Protobuf官方库提供了UnknownFieldSet类,可直接解析无Schema的Protobuf二进制数据,无需依赖.proto文件。

先确保安装protobuf库:

pip install protobuf

然后使用以下代码:

import json
from google.protobuf.unittest_pb2 import UnknownFieldSet
from google.protobuf.json_format import MessageToDict

# 假设blob是你的Protobuf二进制数据(bytes类型)
unknown_fields = UnknownFieldSet()
unknown_fields.ParseFromString(blob)

# 转换为字典后转JSON
result_dict = MessageToDict(unknown_fields, preserving_proto_field_name=True)
json_result = json.dumps(result_dict, indent=2)
print(json_result)

该方法直接解析二进制Blob,无需调用外部protoc命令,适合纯Python环境。输出的JSON键为字段编号,嵌套结构会自动处理。


内容的提问来源于stack exchange,提问作者Georg K.

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.03 17:51:29