Retrieving specific data from a .json file more efficiently?
<p>I have the following <code>.json</code> file, which have some lists like values in some elements:</p>

<pre><code>{
  "paciente": [
    {
      "id": 1234,
      "nombre": "Pablo",
      "sesion": [
        {
          "id": 12345,
          "juego": [
            {
              "nombre": "bonzo",
              "nivel": [
                {
                  "id": 1234,
                  "nombre": "caida libre"
                }
              ],
              "___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
                }
              ]
            }
          ],
          "segmento": [
            {
              "id": 12345,
              "nombre": "Hombro",
              "movimiento": [
                {
                  "id": 12,
                  "nombre": "flexion",
                  "metricas": [
                    {
                      "min": 12,
                      "max": 34,
                      "media": 23,
                      "moda": 20
                    }
                  ]
                }
              ]
            }
          ]
        }
      ]
    },
    {
      "id": 156,
      "nombre": "Bernardo",
      "sesion": [
        {
          "id": 456,
          "juego": [
            {
              "nombre": "Rita",
              "nivel": [
                {
                  "id": 1,
                  "nombre": "NAVEGANDO"
                }
              ],
              "___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
                }
              ]
            }
          ],
          "segmento": [
            {
              "id": 12345,
              "nombre": "Escapula",
              "movimiento": [
                {
                  "id": 12,
                  "nombre": "ProtracciÃ³n",
                  "metricas": [
                    {
                      "min": 12,
                      "max": 34,
                      "media": 23,
                      "moda": 20
                    }
                  ]
                }
              ]
            }
          ]
        }
      ]
    }
  ]
}
</code></pre>

<p>From my script, I want to go through it's different nested elements for get specific information</p>

<pre><code>import json

with open('myfile.json') as data_file:
    data = json.loads(data_file.read())


    patient_id = data["paciente"][0]["id"]

    patient_name = data["paciente"][0]["nombre"]

    id_session = data["paciente"][0]["sesion"][0]["id"]

    game_session = data["paciente"][0]["sesion"][0]["juego"][0]["nombre"]

    level_game = data["paciente"][0]["sesion"][0]["juego"][0]["nivel"][0]["nombre"]

    iterations = data["paciente"][0]["sesion"][0]["juego"][0]["iteraciones"]

    iterations_victory = data["paciente"][0]["sesion"][0]["juego"][0]["iteraciones"][0]["victoria"]

    iterations_time = data["paciente"][0]["sesion"][0]["juego"][0]["iteraciones"][0]["tiempo"]

    iterations_victory1 = data["paciente"][0]["sesion"][0]["juego"][0]["iteraciones"][1]["victoria"]

    iterations_time1 = data["paciente"][0]["sesion"][0]["juego"][0]["iteraciones"][1]["tiempo"]

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

    movement = data["paciente"][0]["sesion"][0]["segmento"][0]["movimiento"][0]["nombre"]

    #metrics = data["paciente"][0]["sesion"][0]["segmento"][0]["movimiento"][0]["metricas"]

    metric_min = data["paciente"][0]["sesion"][0]["segmento"][0]["movimiento"][0]["metricas"][0]["min"]

    metric_max = data["paciente"][0]["sesion"][0]["segmento"][0]["movimiento"][0]["metricas"][0]["max"]

    metric_average = data["paciente"][0]["sesion"][0]["segmento"][0]["movimiento"][0]["metricas"][0]["media"]

    metric_moda = data["paciente"][0]["sesion"][0]["segmento"][0]["movimiento"][0]["metricas"][0]["moda"]

    print(
        'Patient ID:', patient_id,'\n',
        'Patient Name:', patient_name, '\n',
        'Session:','\n',
        '  Id Session:',id_session,'\n',
        '  Game:', game_session, '\n',
        '  Level:', level_game, '\n',
        '  Iterations:', len(iterations),'\n',
        '    Victory:', iterations_victory, '\n',
        '    Time:', iterations_time, '\n',
        '    Victory:', iterations_victory1, '\n',
        '    Time:', iterations_time1, '\n',
        '  Affected Segment:', segment, '\n',
        '    Movement:', movement, '\n',
        '       Metrics:','\n',
        '          Minimum:', metric_min, '\n'
        '          Maximum:', metric_max, '\n'
        '          Average:', metric_average, '\n'
        '          Moda/Trend:', metric_moda, '\n'

        )
</code></pre>

<p>This is my output:</p>

<pre class="lang-none prettyprint-override"><code>Patient ID: 1234
 Patient Name: Pablo
 Session:
   Id Session: 12345
   Game: bonzo
   Level: caida libre
   Iterations: 2
     Victory: True
     Time: 120
     Victory: False
     Time: 232
   Affected Segment: Hombro
     Movement: flexion
        Metrics:
           Minimum: 12
          Maximum: 34
          Average: 23
          Moda/Trend: 20

[Finished in 0.0s]
</code></pre>

<p>Is it possible to optimize this code?
How to can I make this code more readable or short?</p>

<p>I would like especially when I will have query for more of one element (just in case of that exist) in the lists/arrays like as segment, movement, iterations, games, etc</p>

<p>Any orientation is welcome.</p>

<p>Depending on what else your program is doing, it may or may not matter if you speed the code up. You should use the <code>profile</code> or <code>cProfile</code> module to find out where your script is spending its time and work on those.</p>

<p>Regardless, you could save some processing time by removing all the redundant indexing operations by using temporary variable to hold the result. You can think of this simple as the removal of common prefixes. It's relatively easy if you've got a good code editor.</p>

<p>Although it may not be shorter or more readable code, it likely will execute faster (although there is some overhead involved).</p>

<p>Here's what I'm describing:</p>

<pre><code>import json

with open('myfile.json') as data_file:
    data = json.loads(data_file.read())

    patient0_data = data["paciente"][0]

    patient_id = patient0_data["id"]
    patient_name = patient0_data["nombre"]

    patient0_data_sesion0 = patient0_data["sesion"][0]

    id_session = patient0_data_sesion0["id"]

    patient0_data_sesion0_juego0 = patient0_data_sesion0["juego"][0]

    game_session = patient0_data_sesion0_juego0["nombre"]
    level_game = patient0_data_sesion0_juego0["nivel"][0]["nombre"]
    iterations = patient0_data_sesion0_juego0["iteraciones"]

    patient0_data_sesion0_juego0_iteraciones = patient0_data_sesion0_juego0["iteraciones"]

    iterations_victory = patient0_data_sesion0_juego0_iteraciones[0]["victoria"]
    iterations_time = patient0_data_sesion0_juego0_iteraciones[0]["tiempo"]
    iterations_victory1 = patient0_data_sesion0_juego0_iteraciones[1]["victoria"]
    iterations_time1 = patient0_data_sesion0_juego0_iteraciones[1]["tiempo"]

    patient0_data_sesion0_segmento0 = patient0_data_sesion0["segmento"][0]

    segment = patient0_data_sesion0_segmento0["nombre"]

    patient0_data_sesion0_segmento0_movimiento0 = (
                                    patient0_data_sesion0_segmento0["movimiento"][0])

    movement = patient0_data_sesion0_segmento0_movimiento0["nombre"]
    #metrics = patient0_data_sesion0_segmento0_movimiento0["metricas"]

    patient0_data_sesion0_segmento0_movimiento0_metricas0 = (
                        patient0_data_sesion0_segmento0["movimiento"][0]["metricas"][0])

    metric_min = patient0_data_sesion0_segmento0_movimiento0_metricas0["min"]
    metric_max = patient0_data_sesion0_segmento0_movimiento0_metricas0["max"]
    metric_average = patient0_data_sesion0_segmento0_movimiento0_metricas0["media"]
    metric_moda = patient0_data_sesion0_segmento0_movimiento0_metricas0["moda"]

    print(
        'Patient ID:', patient_id,'\n',
        'Patient Name:', patient_name, '\n',
        'Session:','\n',
        '  Id Session:',id_session,'\n',
        '  Game:', game_session, '\n',
        '  Level:', level_game, '\n',
        '  Iterations:', len(iterations),'\n',
        '    Victory:', iterations_victory, '\n',
        '    Time:', iterations_time, '\n',
        '    Victory:', iterations_victory1, '\n',
        '    Time:', iterations_time1, '\n',
        '  Affected Segment:', segment, '\n',
        '    Movement:', movement, '\n',
        '       Metrics:','\n',
        '          Minimum:', metric_min, '\n'
        '          Maximum:', metric_max, '\n'
        '          Average:', metric_average, '\n'
        '          Moda/Trend:', metric_moda, '\n'

        )
</code></pre>

python arrays json