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

How to read key value in JSON output without using index

Here is a sample JSON output myJSON:

{ "results": [
    {
      "data1": 123.45,
      "data2": 67.89
    }
  ]
}

I’m trying to directly read data1:

mydata1 = myJSON['data1']

I get an error KeyError: 'data1'. I can only find a way to do this by using an index:

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

mydata1 = myJSON['results'][0]['data1']

Is there a way to directly read the value in data1 without having to specify an index for results? Or is an index required? Just trying to find a more compact / elegant solution here.

>Solution :

Your json is :

myJSON = {

    "results": [
        {
          "data1": 123.45,
          "data2": 67.89
        }
      ]
}

If you want to get data1 without using index you can use for loop. this will take O(N) time:

for x in myJSON["results"]:
  mydata1 = x['data1']

print(mydata1)
#123.45

Or List comprehension:

mydata1 = [x['data1'] for x in myJSON["results"]]

print(*mydata1)
#123.45

Ideally,it should be with O(1) time

mydata1 = myJSON['results'][0]['data1']

Or

mydata1 = myJSON['results'][-1]['data1']
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