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)
所以总结:我想输出的JSON有空的对象,但它们将被忽略。
编辑:在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
键 - 这是问题。
在此先感谢
使用'2.0.9'版本,它能够在结果字符串中生成空列表:''json.dumps({'foo':[]})'''''“foo”:[]}''。它和你的选择一样好。 – Emilien
我们需要一个[mcve]。 –
@Emilien你确实是对的。这对我来说可以。我的同事(谁有问题)必须运行旧版本。会发现。谢谢 – Chris