I am getting the error when I try to run the following code. I know it has something to do with the formating of the json file but I am not sure how to proceed/change in order to be able to get floats from the json file
JavaScript
x
4
1
print(location['latitude'])
2
TypeError: string indices must be integers
3
4
my code
JavaScript
1
26
26
1
import requests
2
import bs4 as bs
3
import urllib.parse
4
import json
5
from datetime import datetime, timedelta
6
import time
7
import re
8
9
10
11
12
url='https://www.vrbo.com/el-gr/%CE%B5%CE%BD%CE%BF%CE%B9%CE%BA%CE%B9%CE%AC%CF%83%CE%B5%CE%B9%CF%82-%CE%B5%CE%BE%CE%BF%CF%87%CE%B9%CE%BA%CF%8E%CE%BD-%CE%BA%CE%B1%CF%84%CE%BF%CE%B9%CE%BA%CE%B9%CF%8E%CE%BD/p436144?adultsCount=2&arrival=2021-05-08&departure=2021-05-16'
13
req = requests.get(url).text
14
15
search = re.search(r'window.__INITIAL_STATE__ = ({.*});', req).group(1)
16
17
data = json.loads(search)
18
19
20
# print(data.keys())
21
22
# print(json_object)
23
24
for location in data['listingReducer']['geoCode']:
25
print(location['latitude'])
26
Advertisement
Answer
data['listingReducer']['geoCode']
is a dict
so doing for location in data['listingReducer']['geoCode']
gives you the keys
JavaScript
1
11
11
1
.
2
.
3
.
4
# print(data.keys())
5
6
# print(json_object)
7
8
# for location in data['listingReducer']['geoCode']:
9
# print(location['latitude'])
10
print(data['listingReducer']['geoCode']['latitude'])
11