pb文件转json文件python脚本

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
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值