from google.protobuf import json_format
import json
import xxxx as pb # <--------- 这里是 proto 编译出来的 py文件
import glob
import os
def pb2json_file(message, pb_file, json_out_file, save_=False, show_=False):
"""用来将pb文件转换为json文件
Args:
message
pb_file (string): 需要转换的 pb 文件路径字符串
json_out_file (string): 输出的 json 文件路径字符串
save_ (bool, optional): 是否保存. Defaults to False. 优先级高于 `json_out_file`
show (bool, optional): 是否显示 pb 文件内容. Defaults to False.
Return:
out_dic: 输出的字典
"""
with open(str(pb_file), "rb") as f:
message.ParseFromString(f.read())
json_str = json_format.MessageToJson(message)
json_obj = json.loads(json_str)
if show_:
# print(json_str)
print(message)
if save_:
with open(json_out_file, "w") as f:
f.write(json_str)
return json_obj
这样调用即可
message = pb.xxxxx() # 这里写 pb 中的名称
pb_file = 'input.pb'
json_file= 'out.json'
json_obj = pb2json_file(message, pb_file, json_file, show_=True, save_=True)
这个API返回的是json字符串,而不是字典
from google.protobuf import json_format
json_format.MessageToJson