2016-06-07 21 views
0

使用Python的json模塊,我希望能夠將空對象/數組輸出到我的JSON中。但是這個模塊似乎忽略了它們。如何使用Python向JSON輸出空對象

我正在使用的遺留代碼的一部分,要求即使爲空也要定義這些對象。

這是代碼:

import json 
import sys 

filename = sys.argv[1] 
with open(filename) as json_file: 
    json_decoded = json.load(json_file) 

json_decoded['empty'] = [] 
json_decoded['not_empty'] = 'allocation' 

with open(filename, 'w') as json_file: 
    json.dump(json_decoded, json_file, sort_keys=True, indent=4) 

所以總結:我想輸出的J​​SON有空的對象,但它們將被忽略。

編輯:在sys.argv中[1]中使用的JSON的一個例子是:

{ 
    "some_text": "hello", 
    "use_google": false, 
    "use_gravatar": false, 
    "empty": [], 
    "not_empty": "some more text" 
} 

代碼基本上讀取在現有JSON,進json_decoded變量,然後我們稍稍改變由設置只是改變了陣列,最後輸出的新數組到文件...

這一切工作正常,但新的JSON將如下:

{ 
    "some_text": "hello", 
    "use_google": false, 
    "use_gravatar": false, 
    "not_empty": "allocation" 
} 

你可以看到它缺少的empty鍵 - 這是問題。

在此先感謝

+0

使用'2.0.9'版本,它能夠在結果字符串中生成空列表:''json.dumps({'foo':[]})'''''「foo」:[]}''。它和你的選擇一樣好。 – Emilien

+0

我們需要一個[mcve]。 –

+0

@Emilien你確實是對的。這對我來說可以。我的同事(誰有問題)必須運行舊版本。會發現。謝謝 – Chris

回答

0

代碼正常工作。我被告知它沒有,我應該檢查。

所以上面的代碼都可以正常工作。

我可以刪除問題還是留在這裏供人們查看?我接受這個答案嗎?