嵌套字典 - 获取值(Python)

时间:2018-01-06 21:59:42

标签: python json dictionary nested

我有一个JSON文件,从XML转换而来,最初是等式:x ^ 2 + 4 * x + 4 = 0:

{
  "mrow": {
    "mrow": {
      "msup": {
        "mi": "x",
        "mn": "2"
      },
      "mo": [
        "+",
        "+"
      ],
      "mrow": {
        "mn": "4",
        "mo": "*",
        "mi": "x"
      },
      "mn": "4"
    },
    "mo": "=",
    "mn": "0"
  }
}

当我用Python打开这个文件时,我会得到嵌套的词典,如下所示:

{'mrow': {'mrow': {'msup': {'mi': 'x', 'mn': '2'}, 'mo': ['+', '+'], 'mrow': {'mn': '4', 'mo': '*', 'mi': 'x'}, 'mn': '4'}, 'mo': '=', 'mn': '0'}}

是否有一种简单的方法只能获得表示初始方程的值,以便我再次得到初始方程?

1 个答案:

答案 0 :(得分:0)

你可以试试这个:

def parse_obj(obj):
    if isinstance(obj, dict):
        items = []
        for key, value in obj.items():
            if key == 'mrow':
                items.append(parse_obj(value))
            elif key == 'msup':
                mi = parse_obj(value['mi'])
                mo = parse_obj(value['mn'])
                items.append("{mi}^{mo}".format(mi=mi, mo=mo))
            elif key in ['mi', 'mo', 'mn']:
                items.append(parse_obj(value))
            else:
                raise NotImplementedError((key, value))
        return " ".join(items)
    elif isinstance(obj, list):
        return " ".join(parse_obj(value) for value in obj)
    else:
        return obj  # a string

使用以下json内容:

text = """\
{
  "mrow": {
    "mrow": {
      "msup": {
        "mi": "x",
        "mn": "2"
      },
      "mo": [
        "+",
        "+"
      ],
      "mrow": {
        "mn": "4",
        "mo": "*",
        "mi": "x"
      },
      "mn": "4"
    },
    "mo": "=",
    "mn": "0"
  }
}"""

json_decoder = json.JSONDecoder(object_pairs_hook=collections.OrderedDict)
obj1 = json_decoder.decode(text)
print(parse_obj(obj1))

你得到:

x^2 + + 4 * x 4 = 0

我认为"mo": ["+", "+"] ...

存在问题