Python 无法将dicts字符串加载到JSON中
代码将返回未包装的Python 无法将dicts字符串加载到JSON中,python,json,dictionary,Python,Json,Dictionary,代码将返回未包装的dicts的字符串。我尝试转储/加载并将其包装在[]中,但出于奇怪的原因,它仍然是一个字符串您需要手动将目标转换为列表,以接收Python对象: import requests import re import json def parser(code): params = { 'template': 'professional', 'level': 'search', 'search': code }
dicts
的字符串。我尝试转储/加载并将其包装在[
]
中,但出于奇怪的原因,它仍然是一个字符串
您需要手动将目标转换为列表,以接收Python对象:
import requests
import re
import json
def parser(code):
params = {
'template': 'professional',
'level': 'search',
'search': code
}
r = requests.get("https://maps.locations.husqvarna.com/api/getAsyncLocations",
params=params).json()
goal = re.search(r'({.+})', r['maplist'], re.M | re.DOTALL).group(1)
print(goal)
parser("35801")
输出:
谢谢,我看到您使用了格式字符串。我一直在尝试[进球],但不知怎么的,它引发了一个例外。你知道为什么format string解决了这个问题吗?[goal]
将生成一个包含一个元素的Python列表。但是您需要一个包含多个JSON对象的JSON数组,这就是为什么需要首先格式化字符串。
import requests
import re
import json
def parser(code):
params = {
'template': 'professional',
'level': 'search',
'search': code
}
r = requests.get("https://maps.locations.husqvarna.com/api/getAsyncLocations",
params=params).json()
goal = re.search(r'({.+})', r['maplist'], re.M | re.DOTALL).group(1)
jsonList = '[%s]' % goal # Make proper json list!
items = json.loads(jsonList)
for item in items:
print(item)
parser("35801")
{'fid': 'USF221344-2115METROCIRCLE', 'lid': '56063', 'lat': '34.7004049', 'lng': '-86.5924508', 'url': 'https://locations.husqvarna.com/al/huntsville/product-manufacturer-usf221344-2115metrocircle.html', 'country': 'US', 'url_slug': 'product-manufacturer-usf221344-2115metrocircle.html', 'location_name': 'HEDDEN LAWN & GARDEN', 'address_1': '2115 METRO CIRCLE', 'address_2': '', 'city': 'HUNTSVILLE', 'city_clean': 'huntsville', 'region': 'AL', 'region_lc': 'al', 'post_code': '35801', 'local_phone': '(256) 885-1750', 'local_phone_pn_dashes': '256-885-1750', 'local_fax': '', 'local_fax_pn_dashes': '', 'from_email': '', 'hours_timezone': '', 'hours_dst': '', 'distance': '2.2', 'hours_sets:primary': '{"label":"Primary Hours","name":"primary","type":"0","timezone":"-6","dst":"1"}', 'Store Type_CS': 'Buy,Service', 'Location Type_CS': 'Authorized Dealers,Servicing Locations'}
...