【问题标题】:How create recursive loop for parsing the json?如何创建用于解析 json 的递归循环?
【发布时间】:2018-07-01 20:08:05
【问题描述】:

我在我的 Django 项目中使用Nestable2 插件来创建树。

当用户更改树节点的顺序时,插件返回我通过 Ajax 发送到服务器的 JSON。

Nestable2 向我返回 JSON:

[{"id":1},{"id":2},{"id":3,"children":[{"id":4},{"id":5,"foo":"bar"}]}]

在 Django 视图中,我采用此 JSON,但我想将其解析为 id 列表。例如:

[1, 2, 3, 4, 5, ...]

在我看来,我需要为此任务创建递归循环,所以我有点困惑。有人能说出完成这项任务的最佳方法吗?

views.py:

class NodeOrderView(CsrfExemptMixin, JsonRequestResponseMixin, FormView):
    def post(self, request, *args, **kwargs):
        print(self.request_json)  # JSON
        return self.render_json_response({'saved': 'ok'})

【问题讨论】:

  • 不太清楚,你想要什么。将JSON 结构展平为每个元素的id
  • 您好! :) 问题看起来很简单,但我很困惑。在帖子中,您可以看到我通过 ajax 发送到服务器的 JSON 示例。我想在我的views.py 文件中从此 JSON 创建 id 列表。我希望用于其他目的的 id 列表。

标签: python json django python-2.7 django-1.11


【解决方案1】:

如果我理解你的问题。这应该做你想要的。或者至少为您指明正确的方向。

json_array = [{"id":1},{"id":2},{"id":3,"children":[{"id":4},{"id":5,"foo":"bar"}]}]

def get_ids(json_array):
    ids = []
    for obj in json_array:
        if isinstance(obj, dict):
            ids.append(obj.get('id'))
            children = obj.get('children', None)
            if children:
                ids.extend(get_ids(children))
        elif isinstance(obj, list):
            ids.extend(get_ids(obj))
    return ids

>>> get_ids(json_array)
[1, 2, 3, 4, 5]

【讨论】:

  • 谢谢你,兄弟! :) 您的通用方法考虑了不同的嵌套深度。效果很好!
  • 没问题,小心。我会对其进行适当的测试并根据需要进行调整。
  • 你为什么害怕?你的意见有什么问题?我测试了不同级别的树嵌套,看起来效果很好。
  • 例如,如果没有 'children' 属性,您可以获得KeyError。或者特定对象的id 标记为something_id。或者嵌套大于递归限制。或者您的一个对象是dictlist 的子类。可能有负载出错...
猜你喜欢
  • 1970-01-01
  • 2018-05-16
  • 2014-01-05
  • 2018-07-18
  • 2011-05-05
  • 1970-01-01
  • 2021-01-07
  • 1970-01-01
  • 2018-09-30
相关资源
最近更新 更多