将 protoc --decode_raw 的输出转换为 json

问题描述 投票:0回答:2

我正在尝试将 protobuf blob 的消息转换为 json,但没有相应的架构。这是我正在使用的代码,但它没有获取嵌套对象。也许有一种方法可以在没有模式的情况下转换 blob?我只需要一个 json 。变量名称对我来说并不重要。

message_dict = {}
for line in result.stdout.split("\n"):
    if not line:
        continue
    parts = line.split(": ")
    field_number = parts[0]
    value = parts[1] if len(parts) > 1 else None
    message_dict[field_number] = value
python protocol-buffers grpc
2个回答
1
投票

您可以根据从

.proto
学到的信息自行编写
--decode_raw
模式。

之后可以使用函数轻松转换为 JSON

google.protobuf.json_format.MessageToJson


1
投票

对任何可能有帮助的人

def proto_to_json():
    try:
        # Run the protoc command
        output = subprocess.run(["protoc", "--decode_raw"],
                                stdin=open("tiktok.txt", "r", encoding="utf-8"),
                                capture_output=True,
                                text=True)
    except UnicodeDecodeError:
        output = subprocess.run(["protoc", "--decode_raw"],
                                stdin=open("tiktok.txt", "r", errors='ignore'),
                                capture_output=True,
                                text=True, stdout=subprocess.PIPE)

    output_lines = output.stdout.strip().split("\n")
    output_lines = [line.strip() for line in output_lines]

    # Define an empty dictionary to store the output
    output_dict = {}

    # Define a stack to keep track of the nested dictionaries
    stack = [output_dict]

    # Iterate through the lines and add the key-value pairs to the dictionary
    for line in output_lines:
        if ": " in line:
            key, value = line.split(": ", 1)
            stack[-1][key] = value
        elif "{" in line:
            key = line.replace("{", "")
            new_dict = {}
            stack[-1][key] = new_dict
            stack.append(new_dict)
        elif "}" in line:
            stack.pop()

    # Convert the dictionary to a JSON string
    json_output = json.dumps(output_dict, indent=4)

    # Write the JSON string to a file
    with open("file_name", "w") as f:
        f.write(json_output)

    return json_output
© www.soinside.com 2019 - 2024. All rights reserved.