Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Parsing JSON values and feeding them in a loop

I have the following JSON code:

"configuration": {
    "contents": [
      {
        "file": "path/page.xhtml",
        "index": 1,
      },
      {
        "file": "path/p-001.xhtml",
        "index": 2,
      },
      {
        "file": "path/p-002.xhtml",
        "index": 3,
      },
      {
        "file": "path/p-003.xhtml",
        "index": 4,
      }
    ]
}

In Python, I wish to feed all the "file" values into an URL in a loop one by one, how should I do so?

Current code: (metadata containing the JSON data)

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

metaconfiguration = metadata['configuration']
metacontents = metaconfiguration['contents']
path = metacontents[s]['file']

Count = 1
while Count < 5:
    url = "https://example.com/"+path
    Count += 1

Note that I will soon replace the "Count" value with the length of "contents" after I will be done with this problem.

Thank you.

>Solution :

You only need to loop over metacontents to find the path elements:

import json

txt = '''{"configuration": {
    "contents": [
      {
        "file": "path/page.xhtml",
        "index": 1
      },
      {
        "file": "path/p-001.xhtml",
        "index": 2
      },
      {
        "file": "path/p-002.xhtml",
        "index": 3
      },
      {
        "file": "path/p-003.xhtml",
        "index": 4
      }
    ]
}}'''

metadata = json.loads(txt)

metaconfiguration = metadata['configuration']
metacontents = metaconfiguration['contents']
for d in metacontents:
    url = 'https://example.com/' + d['file']
    print(url)

Output:

https://example.com/path/page.xhtml
https://example.com/path/p-001.xhtml
https://example.com/path/p-002.xhtml
https://example.com/path/p-003.xhtml
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading