I’m pretty new to json, I try to parse two elements (multiple occurences), I’m pretty sure I don’t iterate correctly.
My json file:
{
"data": {
"chapter": {
"bibleId": "9f3cb709f9bded60-01",
"bookId": "PSA",
"id": "PSA.117",
"content": [
{
"type": "paragraph",
"style": "nb",
"content": [
{
"type": "verse-number",
"style": "v",
"verseId": "PSA.117.1",
"verseOrgId": [
"PSA.117.1"
],
"content": "1"
},
{
"type": "verse-text",
"verseId": "PSA.117.1",
"verseOrgId": [
"PSA.117.1"
],
"verseText": "Sed ut perspiciatis unde omnis iste natus."
},
{
"type": "verse-number",
"style": "v",
"verseId": "PSA.117.2",
"verseOrgId": [
"PSA.117.2"
],
"content": "2"
},
{
"type": "verse-text",
"verseId": "PSA.117.2",
"verseOrgId": [
"PSA.117.2"
],
"verseText": "Lorem ipsum dolor sit amet."
}
]
}
],
"number": "117",
"next": {
"id": "PSA.118",
"bookId": "PSA",
"number": "118"
},
"previous": {
"id": "PSA.116",
"bookId": "PSA",
"number": "116"
},
"copyright": "1969/77 Deutsche Bibelgesellschaft, Stuttgart",
"verseCount": 2,
"title": "Psalmi 117"
},
"studyContent": null,
"chapterImage": null
}
}
Desired output:
PSA.117.1 Sed ut perspiciatis unde omnis iste natus.
PSA.117.2 Lorem ipsum dolor sit amet.
My output:
PSA.117.1 Sed ut perspiciatis unde omnis iste natus.
My code:
import json
with open('data.json') as f:
data = json.load(f)
for i, verse in enumerate(data['data']['chapter']['content']):
if i == 0:
print("%st%s" % (verse['content'][0]['verseId'], verse['content'][1]['verseText']))
elif i == 1:
print("%st%s" % (verse['content'][0]['verseId'], verse['content'][1]['verseText']))
3
Answers
The issue in your script lies in the way you’re iterating through the JSON structure and accessing the verse data.
The JSON structure you’ve provided has an array content within data[‘data’][‘chapter’][‘content’], which contains only one item (a paragraph), and then within that paragraph, it has an array content containing the verses.
You want one more loop over the inner
content
list, and filter the nodes which are oftype
verse-text
: