Home > OS >  How to iterate through nested JSON with unique IDs?
How to iterate through nested JSON with unique IDs?

Time:06-14

I'm working with a JSON object that lists every entry as a nested JSON object within DynamoDB. Each entry has a unique id generated as the JSON identifier. I'm trying to loop through each nested JSON entry entry and grab all of the values associated with that entry (ex."entry.34d6fd1269dd450cbe2437b942d68513.employeeLevel). Not sure how to for loop through each nested JSON entry without knowing the entry id. How would you go about this? The JSON object structure is listed below:

{
     "username": "test",
     "entry": {
      "34d6fd1269dd450cbe2437b942d68513": {
       "employeeLevel": "level one",
       "body": "Test 1",
       "cloudPlatformAoi": [
        "IBM Cloud or Watson"
       ],
       "cloudPlatformStrength": [
        "AWS"
       ],
       "databaseStrength": [
        "DynamoDB"
       ],
       "dbAoi": [
        "MySQL",
        "OpenSearch"
       ],
       "integratedDevelopmentEnvironment": [
        "PyCharm",
        "Sublime Text"
       ],
       "integratedDevelopmentEnvironmentAoi": [
        "PyCharm",
        "Sublime Text"
       ],
       "lastEdited": "09-Jun-2022 (13:31:13.095137)",
       "programmingLanguageAoi": [
        "CDK"
       ],
       "programmingLanguageStrength": [
        "CDK",
        "Java",
        "Python",
        "TypeScript"
       ],
       "timeCreated": "09-Jun-2022 (13:30:29.967379)",
       "title": "This is my first post (Edited)",
       "webFrameworkAoi": [
        "Laravel",
        "Ruby on Rails"
       ],
       "webFrameworkStrength": [
        "Flask"
       ]
      },
      "34dc811470ee459ab06ec70a1010b6b4": {
       "employeeLevel": "level two",
       "body": "Hello World 2!",
       "cloudPlatformAoi": [
        "Heroku"
       ],
       "cloudPlatformStrength": [
        "AWS"
       ],
       "databaseStrength": [
        "Couchbase"
       ],
       "dbAoi": [
        "Oracle"
       ],
       "integratedDevelopmentEnvironment": [
        "Vim"
       ],
       "integratedDevelopmentEnvironmentAoi": [
        "Vim"
       ],
       "lastEdited": "09-Jun-2022 (14:30:28.864071)",
       "programmingLanguageAoi": [
        "Elixir"
       ],
       "programmingLanguageStrength": [
        "Assembly"
       ],
       "timeCreated": "09-Jun-2022 (13:30:29.967379)",
       "title": "2 (edited)",
       "webFrameworkAoi": [
        "Spring"
       ],
       "webFrameworkStrength": [
        "jQuery"
       ]
      }
     },
     "useremail": "[email protected]"
    }

CodePudding user response:

You can capture the dictionary under entry by d['entry'] (after loading the json into d), then iterate over each key under entry (assuming the keys under entry are the entry ids) and capture the dictionary for each entry id by entry[id]

d = json.loads(s)
entry = d['entry']
for id in entry:
    do_something(entry[id])
  • Related