0

我正在尝试通过遍历包含此数据的图形来创建以下 JSON 文本:

{
"random" : [
    {
        "attr1" : "X",
        "attr2" : "Y"
    },
    {
        "attr1" : "Z",
        "attr2" : "V"
    }
    ]
}

我试过这个:

output = ""
for node in graph:
    output += json.JSONEncoder().encode({"random": [{"attr1": graph[node].attr1, "attr2":graph[node].attr2}]})

但这会导致在每个条目之前重复“随机”,如下所示:

{"random": [{"attr1": "X", "attr2": "Y"}]}{"random": [{"attr1": "Z", "attr2": "V"}]}

如何防止“随机:”被重复?任何建议表示赞赏,谢谢。

4

2 回答 2

2

您是否有任何理由为单独的节点连接字符串,而不是一次转储整个结构?

>>> import json
>>> graph = {
... "random" : [
...     {
...         "attr1" : "X",
...         "attr2" : "Y"
...     },
...     {
...         "attr1" : "Z",
...         "attr2" : "V"
...     }
...     ]
... }
>>> json.dumps(graph)
'{"random": [{"attr2": "Y", "attr1": "X"}, {"attr2": "V", "attr1": "Z"}]}'

首先,它更简单、更快捷。其次,您的连接甚至不会产生有效的 JSON。

于 2013-10-03T05:07:36.513 回答
0

我不确定你为什么要循环,但你可以简单地对图形对象进行编码。

import json
graph = { "random": [ { "attr1": "X", "attr2": "Y"}, {"attr1": "Z", "attr2": "V"}]}
output = json.JSONEncoder().encode(graph)
print output
# yields '{"random": [{"attr2": "Y", "attr1": "X"}, {"attr2": "V", "attr1": "Z"}]}'
于 2013-10-03T05:12:08.630 回答