programing

비단뱀의 protobuf to json

lastmoon 2023. 3. 23. 23:05
반응형

비단뱀의 protobuf to json

를 사용하여 시리얼을 해제하는 오브젝트가 있다.protobufPython에서.오브젝트를 인쇄할 때는 python 오브젝트처럼 보이지만 변환하려고 하면json여러 가지 문제가 있어요.

예를 들면,json.dumps()오브젝트(protoc에서 생성된 코드)에 _dict_ 오류가 포함되어 있지 않습니다.

jsonpickle을 사용하면 얻을 수 있습니다.UnicodeDecodeError: 'utf8' codec can't decode byte 0x9d in position 97: invalid start byte.

다음 테스트 코드가 사용되고 있습니다.jsonpickle에러가 표시됩니다.

if len(sys.argv) < 2:
    print ("Error: missing ser file")
    sys.exit()
else :
    fileLocation = sys.argv[1]

org = BuildOrgObject(fileLocation) 

org = org.Deserialize()


#print (org)
jsonObj = jsonpickle.encode(org)
print (jsonObj)

Google의 protobuf 라이브러리에서 protobuf↔json 변환기를 사용하는 것이 좋습니다.

from google.protobuf.json_format import MessageToJson

json_obj = MessageToJson(org)

protobuf를 사전에 시리얼화할 수도 있습니다.

from google.protobuf.json_format import MessageToDict
dict_obj = MessageToDict(org)

protobuf 패키지 API 매뉴얼을 참조하십시오.https://developers.google.com/protocol-buffers/docs/reference/python/ (모듈 참조).google.protobuf.json_format).

json으로 바로 이동해야 하는 경우 protobuf-to-json 라이브러리를 살펴보십시오. 단, 수동으로 설치해야 합니다.

그러나 몇 가지 이유로 protobuf-to-dict 라이브러리를 사용하는 것이 좋습니다.

  1. pypi에서 액세스 할 수 있기 때문에, 간단하게pip install protobuf-to-dict또는 에 포함시킬 수도 있습니다.requirements.txt
  2. dictjson으로 변환할 수 있으며 json 문자열보다 더 유용할 수 있습니다.

유저의 시리얼라이즈도 가능합니다.ToString.

org.SerializeToString()

proto3 개체를 JSON 개체로 변환하는 기능은 다음과 같습니다(예: Python 사전).

def protobuf_to_dict(proto_obj):
    key_list = proto_obj.DESCRIPTOR.fields_by_name.keys()
    d = {}
    for key in key_list:
        d[key] = getattr(proto_obj, key)
    return d

Google의 Protobuf 라이브러리에서 변환기가 3.19 버전에서 작동하지 않는 경우가 있기 때문에, 이 함수는 각 Protobuf 개체에 있는 Descriptor 클래스를 활용합니다.

여기서,getattr(obj, string_attribute)에 의해 지정된 값을 반환합니다.obj.attribute

preserving_proto_field_name 필드가 없는 오래된 버전을 사용하는 경우:

from google.protobuf.json_format import MessageToJson
def proto_to_json(proto_obj):
    json_obj = MessageToJson(proto_obj):
    json_obj = MessageToJso, including_default_value_fields=True)
    # Change lowerCamelCase of google Json conversion to the snake_case as in original protobuf
    dict_obj = dict((re.sub(r'(?<!^)(?=[A-Z])', '_', k).lower(),v) for k, v in json.loads(json_obj).items())
    if hasattr(proto_obj, 'uuid'):
        dict_obj["uuid"] = proto_obj.uuid.encode("hex")
    return json.dumps(dict_obj, indent=4, sort_keys=True)

언급URL : https://stackoverflow.com/questions/19734617/protobuf-to-json-in-python

반응형