skip to Main Content

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:

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.

2

Answers


  1. 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']
    
    Login or Signup to reply.
  2. There is much a simpler way.
    I would do that with this technique:

    myJSON = myJSON['results'][0]
    

    Now you can directly access data1 and data2

    print(myJSON['data1'])
    

    And the output will be 123.45

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search