[英]Convert the output of protoc --decode_raw into json
我正在嘗試將 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
您可以根據從--decode_raw
中學到的信息自己編寫.proto
模式。
之后,很容易使用 function google.protobuf.json_format.MessageToJson
。
對可能有幫助的人
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
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.