写protobuf的对象到JSON文件
我有这样old.JSON
文件:写protobuf的对象到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
文件?
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.
这是很明显,这个函数将返回字符串类型的只有一个对象。这个字符串包含很多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和你回来......你几乎什么得到你的问题的底部。让一切正常工作变得很酷
(我说的差不多,因为这些链接之一,加上自身的一些新行,没有明显的原因。如果你有第一个链接对其进行编码,然后将它与第二个进行解码,这是确切的。)
但这不是你想要的答案,因为你不想对数据结构进行双重json化。你只是想序列化到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)
是的,MessageToJson看起来不错,但会导致新问题http://*.com/questions/43835243/google-protobuf-json-format-messagetojson-changes-names-of-fields-how-to-avoid –
以何种方式在此不喜欢原来的?我注意到它不在列表中。这是问题吗? – tdelaney
@tdelaney是的,它不是一个列表。它具有“而不仅仅是”,并且\ n是明确的。 –
您是否直接试过'jsfile.write(MessageToJson(item))'? – Psidom