簡體   English   中英

將protobuf對象寫入JSON文件

[英]Write protobuf objects to JSON file

我有這么old.JSON文件:

[{
    "id": "333333",
    "creation_timestamp": 0,
    "type": "MEDICAL",
    "owner": "MED.com",
    "datafiles": ["stomach.data", "heart.data"]
}]

然后我基於.proto文件創建一個對象:

message Dataset {
  string id = 1;
  uint64 creation_timestamp = 2;
  string type = 3;
  string owner = 4;
  repeated string datafiles = 6;
}

現在我要保存此對象,將此對象保存回其他.JSON文件。 我這樣做了:

import json
from google.protobuf.json_format import MessageToJson

with open("new.json", 'w') as jsfile:
    json.dump(MessageToJson(item), jsfile)

結果我有:

"{\n  \"id\": \"333333\",\n  \"type\": \"MEDICAL\",\n  \"owner\": \"MED.com\",\n  \"datafiles\": [\n    \"stomach.data\",\n    \"heart.data\"\n  ]\n}"

如何使這個文件看起來像old.JSON文件?

https://developers.google.com/protocol-buffers/docs/reference/python/google.protobuf.json_format-pysrc

31  """Contains routines for printing protocol messages in JSON format. 
32   
33  Simple usage example: 
34   
35    # Create a proto object and serialize it to a json format string. 
36    message = my_proto_pb2.MyMessage(foo='bar') 
37    json_string = json_format.MessageToJson(message) 
38   
39    # Parse a json format string to proto object. 
40    message = json_format.Parse(json_string, my_proto_pb2.MyMessage()) 
41  """ 

 89 -def MessageToJson(message, including_default_value_fields=False): 
...
 99    Returns: 
100      A string containing the JSON formatted protocol buffer message. 

很明顯,這個函數將只返回一個string類型的對象。 這個字符串包含很多json結構,但就python而言,它仍然只是一個字符串。

然后將它傳遞給一個函數,該函數接受一個python對象(不是json),並將其序列化為json。

https://docs.python.org/3/library/json.html

json.dump(obj, fp, *, skipkeys=False, ensure_ascii=True, check_circular=True, allow_nan=True, cls=None, indent=None, separators=None, default=None, sort_keys=False, **kw)

Serialize obj as a JSON formatted stream to fp (a .write()-supporting file-like object) using this conversion table.

好吧,你究竟如何將字符串編碼為json? 顯然,它不能只使用json特定字符,因此必須對其進行轉義。 也許有一個在線工具,如http://bernhardhaeussner.de/odd/json-escape/http://www.freeformatter.com/json-escape.html

你可以去那里,從你的問題的頂部發布起始json,告訴它生成正確的json,然后你回來......幾乎正是你在問題的底部得到的。 酷一切正常!

(我說幾乎是因為其中一個鏈接自己添加了一些換行符,沒有明顯的原因。如果用第一個鏈接對它進行編碼,那么用第二個鏈接對它進行解碼,這是完全正確的。)

但這不是你想要的答案,因為你不想雙重jsonify數據結構。 您只想將其序列化為json一次,並將其寫入文件:

import json
from google.protobuf.json_format import MessageToJson

with open("new.json", 'w') as jsfile:
    actual_json_text = MessageToJson(item)
    jsfile.write( actual_json_text )

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM