使用特定格式将Python字典转换为JSON

时间:2015-10-12 00:43:58

标签: python json dictionary

我正在使用python使用数据列来解析excel电子表格,以创建分层树结构。我已成功将其解析为python字典,我可以将其转换为以下格式:

{
  "1": {
    "1a": [
      "Apple",
      "Orange"
    ],
    "1b": [
      "Horse"
    ]
  },
  "2": {
    "2b": [
      "Spinach",
      "Nut"
    ]
  }
}

但是我需要将它转换为最终的json输出格式:

[
    {
      "name":"1",
      "children": [
        {
          "name":"1a",
          "children":
          [
            {"name":"Apple"},
            {"name":"Orange"}
          ]
        },
        {
          "name":"1b",
          "children": [
            {"name":"Horse"}
          ]
        }
      ]
    },
    {
      "name":"2",
      "children": [
        {
          "name":"2b",
          "children": [
            {"name":"Spinach"},
            {"name":"Nut"}
          ]
        }
      ]
    }
]

有没有办法操纵python字典或改变json来实现这个目的?
我是python的新手,我觉得这里肯定有一些东西。

3 个答案:

答案 0 :(得分:2)

您的输出JSON不太正确,但这显示了如何生成类似的东西(它缺少几个列表/数组括号):

src = {
    "1": {
        "1a": [
        "Apple",
        "Orange"
        ],
        "1b": [
        "Horse"
        ]
    },
    "2": {
        "2b": [
        "Spinach",
        "Nut"
        ]
    }
}

dst =   [{
        "name":"1",
        "children": [
        {
            "name":"1a",
            "children":
            [
            {"name":"Apple"},
            {"name":"Orange"}
            ]
        },
        {
            "name":"1b",
            "children": [
            {"name":"Horse"}
            ]
        }
        ]
    },
    {
        "name":"2",
        "children": [
        {
            "name":"2b",
            "children": [
            {"name":"Spinach"},
            {"name":"Nut"}
            ]
        }
        ]
    }
]

def fixup(what):
    if isinstance(what, str):
        return dict(name=what)
    elif isinstance(what, list):
        return [fixup(x) for x in what]
    else:
        assert isinstance(what, dict)
        return [dict(name=x, children=fixup(y)) for x, y in sorted(what.items())]

assert fixup(src) == dst

答案 1 :(得分:1)

它是关于重新格式化你的数据而不是json it self,

这里我想出了什么,这有点令人困惑

import json
x = {"1": {"1a": ["Apple", "Orange"], "1b": ["Horse"]}, "2": {"2b": ["Spinach", "Nut"]}}
def conv(k, v):
    return {"name": k, "children": list({"name": x, "children": list({"name": z}  for z in v[x])} for x in v)}
print json.dumps(list(conv(k, x[k]) for k in x), indent=4)

我希望它会有所帮助

答案 2 :(得分:0)

您的问题中显示的JSON输出缺少一些括号字符。无论如何,我认为你应该做的是将你所拥有的分层树结构重新格式化为json转储所需的结构:

import json

tree = {
  "1": {
    "1a": [
      "Apple",
      "Orange"
    ],
    "1b": [
      "Horse"
    ]
  },
  "2": {
    "2b": [
      "Spinach",
      "Nut"
    ]
  }
}

objects = [
    {'name': branch,
     'children': [
        {'name': subbranch,
         'children': [{'name': subchild} for subchild in subchildren]
        } for subbranch, subchildren in children.items()
     ]
    } for branch, children in tree.items()
]

print(json.dumps(objects, indent=2))