[Python] How to use index to find position of JSON record

Discussão em 'Python' iniciado por Stack, Agosto 2, 2025.

  1. Stack

    Stack Membro Participativo

    Is there a better way than iteration using a for loop to find the index of the record?

    My problem is that to use index I seem to need the index of the record I'm seeking.

    import json
    from bs4 import BeautifulSoup as BS

    html = '''<html>
    <body>
    <div id="__next">
    </div>
    <script id="__NEXT_DATA__" type="application/json">
    {"topic": "Chemo tablets make me feel sick",
    "id": 152210029,
    "body": "Venetoclax with or without food make me feel sick for 3 hours.\n\n",
    "dateCreated": "2025-07-31T15:20:15.000Z",
    "responses": [
    { "id": 152211099,
    "body": "I was able to survive the nausea with room temperature ginger beer. Don't know why, but it worked!\n\n",
    "dateCreated": "2025-07-31T17:24:35.000Z"
    },
    { "id": 152211304,
    "body": "Sucking on root ginger is good for sea sickness.\n\n",
    "dateCreated": "2025-07-31T19:00:09.000Z"
    },
    { "id": 152211658,
    "body": "Ginger apparently contains a bioactive compound called gingerol. I might give it a try. Healthier than chips!\n\n",
    "dateCreated": "2025-07-31T21:48:15.000Z"
    }]
    }
    </script>
    </body>
    </html>'''

    soup_page = BS(html, 'lxml')
    #print(soup_page.prettify())
    json_script = soup_page.find('script', type='application/json').text
    #print(res)
    json_data = json.loads(json_script, strict=False)
    #print(json_data)
    seek = 152211304
    rec_no = 0
    for record in json_data['responses']:
    # print(record['id'])
    if (record['id'] == seek):
    break
    rec_no = rec_no + 1
    extract = json_data['responses'][rec_no]['body']
    print(extract)

    Continue reading...

Compartilhe esta Página