Home > front end >  How to parse JSON with a list of lists?
How to parse JSON with a list of lists?

Time:01-17

I am trying to parse a "complicated" JSON string that is returned to me by an API.

It looks like this:

{
  "data":[
    ["Distance to last strike","23.0","miles"],
    ["Time of last strike","1/14/2022 9:23:42 AM",""],
    ["Number of strikes today","1",""]
  ]
}

While the end goal will be to extract the distance, date/time, as well as count, for right now I am just trying to successfully get the distance.

My python script is:

import requests
import json
response_API = requests.get('http://localhost:8998/api/extra/lightning.json')
data = response_API.text
parse_json = json.loads(data)
value = parse_json['Distance to last strike']
print(value)

This does not work. If I change the value line to

value = parse_json['data']

then the entire string I listed above is returned.

I am hoping it's just a simple formatting issue. Suggestions?

CodePudding user response:

You have an object with a list of lists. If you fetch

value = parse_json['data']

Then you will have a list containing three lists. So:

print(value[0][1])

will print "23.0".

  •  Tags:  
  • Related