【问题标题】:How to read the json file of a dynamical way in relation to their size structure如何以动态方式读取与其大小结构相关的json文件
【发布时间】:2017-02-12 20:30:26
【问题描述】:

我有以下名为 ProcessedMetrics.json 的 JSON 文件,这是将它们的值发送到某个模板所必需的读取:

     {
  "paciente": {
    "id": 1234,
    "nombre": "Pablo Andrés Agudelo Marenco",
    "sesion": {
      "id": 12345,
      "juego": [
        {
          "nombre": "bonzo",
          "nivel": [
            {
              "id": 1234,
              "nombre": "caida libre",
              "segmento": [
                {
                  "id": 12345,
                  "nombre": "Hombro",
                  "movimiento": [
                    {
                      "id": 1234,
                      "nombre": "flexion",
                      "metricas": [
                        {
                          "min": 12,
                          "max": 34,
                          "media": 23,
                          "moda": 20
                        }
                      ]
                    }
                  ]
                }
              ],
              "___léeme___": "El array 'iteraciones' contiene las vitorias o derrotas con el tiempo en segundos de cada iteración",
              "iteraciones": [
                {
                  "victoria": true,
                  "tiempo": 120
                },
                {
                  "victoria": false,
                  "tiempo": 232
                }
              ]
            }
          ]
        }
      ]
    }
  }
}

通过以下基于类的视图,我正在读取 JSON 文件。

class RehabilitationSessionDetail(LoginRequiredMixin,DetailView):
    model = RehabilitationSession
    template_name = 'rehabilitationsession_detail.html'

    def get_context_data(self, **kwargs):
        context=super(RehabilitationSessionDetail, self).get_context_data(**kwargs)
        is_auth=False

        user = self.request.user
        if user.is_authenticated():
            is_auth=True

            with open('ProcessedMetrics.json') as data_file:
                session_data=json.loads(data_file.read())

            #Sending a data to template
                       context.update({'is_auth':is_auth,
                                       'session_data':session_data
                                     })
       return context

在我的模板rehabilitationsession_detail.html我把我的标签是这样的:

<td>{{session_data.paciente.sesion.juego}}</td> 

然后我在我的模板中获取文档 json

在我的模板中,我想以一种单独的方式获取字典(在 json 文档之前)值,如下所示:

这个想法是,无论 json 文档的嵌套级别如何,我都可以获得值。有时,json 文档在其结构中会有更多的标识级别,而其他时候会是更简单的 json 文档

我希望独立于 json 文档大小(如果数组中有多个项目)可以读取并获取所有值。

我尝试通过这种方式从RehabilitationSessionDetail 视图访问特定项目:

segment = data["paciente"]["sesion"]["juego"][0]["nivel"][0]["segmento"][0]["nombre"]

这可行,但并非总是我会得到相同的 json 文档结构。

总之,如何获取我的 json 文档的值(嵌套和父级)以将它们发送到模板?

我希望我的问题可以清楚。任何方向都非常优雅

【问题讨论】:

    标签: json python-3.x django-templates django-views


    【解决方案1】:

    如果我从您的问题中理解正确,那么不同的 JSON 大小意味着不同的数组大小?您可以循环输入 django 模板以获取所有信息。所以你会做一个嵌套的可视化:

    {% for nest1 in data["patiente"]["sesion"]["juego"] %}
    <li>{{ nest1["nombre"] }}</li>
    {% for nest2 in nest2["nivel"] %}
    etc...
    {% endfor %}
    {% endfor %}
    

    要将其作为表格,您需要分离数据并为每个表格列创建一个循环

    <tr>
        {% for nest1 in data["patiente"]["sesion"]["juego"] %}
        <td>{{ nest1["nombre"] }}</td>
        {% endfor %}
    </tr>
    
    <tr>
        {% for nest1 in data["patiente"]["sesion"]["juego"] %}
        {% for nest2 in nest2["nivel"] %}
        <td>{{ nest2["relevant_key"] }}</td>
        {% endfor %}
        {% endfor %}
    </tr>
    etc...
    

    由于嵌套的 json 数据表示,您的模板代码必须遵循这种嵌套。

    希望我正确理解了您的问题,希望对您有所帮助。

    【讨论】:

    • @levllime 感谢您的方法,这意味着我需要在每一行/列中进行一些循环迭代。我有可能有一些表现情况吗?我会用一些工具或一些相关的来检查这个......
    • @bgarcial 这绝对不如在你的 json 中有一个未嵌套的数据模型那么快。加速是首先将嵌套的 json 列表转换为未嵌套的 json,然后再将其放入 django 模板中。
    猜你喜欢
    • 2021-06-02
    • 2015-07-21
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-02-29
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多