Search code examples
pythonstringbeautifulsoupdata-extraction

How do I locate string and integer data in python


I would like to locate this data from a page source

"location": {"latitude": 35.4677026, "longitude": -80.6093396}

currently I am running this code

floats = re.findall(r"[-+]?\d+\.\d+", str(soup))
  for i in range(len(floats)):
      if len(floats[i]) > 9:
        LatLong.append(floats[i])

The output has the data I am looking for, but it also has data I don't want with it mixed in


Solution

  • import json
    
    string_data = '{"location": {"latitude": 35.4677026, "longitude": -80.6093396}}'
    
    data = json.loads(string_data)
    
    if 'location' in data:
        # do something with the data
        print(data['location']['latitude'])
        print(data['location']['longitude'])
    

    You should verify if the used keys exist in the data dictionary for avoid dictionary keys errors