Skip to content

Instantly share code, notes, and snippets.

@MizunagiKB
Last active March 20, 2022 04:34
Show Gist options
  • Save MizunagiKB/d4a300759770111a034ba267d5d411a8 to your computer and use it in GitHub Desktop.
Save MizunagiKB/d4a300759770111a034ba267d5d411a8 to your computer and use it in GitHub Desktop.
jsonを読み込んでProtocol buffersで定義された形式でバイナリを出力するPythonコードのサンプル
import google.protobuf.json_format
import test_pb2
# test.proto
# $ protoc --python_out=. test.proto
"""
syntax = "proto3";
message Test {
bool b_value = 1;
string s_value = 2;
int32 i_value = 3;
float f_value = 4;
}
"""
JSON_TEXT = """{
"b_value": true,
"s_value": "0123456789ABCDEF",
"i_value": 123,
"f_value": 3.1415
}"""
def main():
pb_obj = test_pb2.Test()
google.protobuf.json_format.Parse(JSON_TEXT, pb_obj)
print(pb_obj)
data = pb_obj.SerializeToString()
# data はバイトデータになっているので、そのままファイルに保存するだけです。
print(data)
if __name__ == "__main__":
main()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment