2017-05-07 166 views
3

我有這樣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文件?

+0

以何種方式在此不喜歡原來的?我注意到它不在列表中。這是問題嗎? – tdelaney

+0

@tdelaney是的,它不是一個列表。它具有「而不僅僅是」,並且\ n是明確的。 –

+0

您是否直接試過'jsfile.write(MessageToJson(item))'? – Psidom

回答

2

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. 

這是很明顯,這個函數將返回字符串類型的只有一個對象。這個字符串包含很多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) 
+0

是的,MessageToJson看起來不錯,但會導致新問題http://stackoverflow.com/questions/43835243/google-protobuf-json-format-messagetojson-changes-names-of-fields-how-to-avoid –