简体   繁体   中英

Why can't I decode the request to JSON?

#!/usr/bin/python3
import re, sys, requests

if len(sys.argv) != 2:
    sys.stderr.write("<Usage> ./script.py message.txt>\n")
    sys.exit(1)

msg = open(sys.argv[1], 'r').read()


group = re.findall(r'(\d+\.\d+)\, (\d+.\d+)', msg)
print(group)
for g in group:
    left_num = float(g[0])
    right_num = float(g[1])
    r = requests.get('https://geocode.xyz/{},{}/json=1'.format(left_num,right_num))
    print(r.json())

I mean, I saw in a different script a really similar thing that worked but for some reason, when I use the .json(), it doesnt let me decode to json

I get this error-

Traceback (most recent call last):
  File "./script.py", line 17, in <module>
    print(r.json())
  File "/home/idoshany/.local/lib/python3.6/site-packages/requests/models.py", line 897, in json
    return complexjson.loads(self.text, **kwargs)
  File "/usr/lib/python3.6/json/__init__.py", line 354, in loads
    return _default_decoder.decode(s)
  File "/usr/lib/python3.6/json/decoder.py", line 339, in decode
    obj, end = self.raw_decode(s, idx=_w(s, 0).end())
  File "/usr/lib/python3.6/json/decoder.py", line 357, in raw_decode
    raise JSONDecodeError("Expecting value", s, err.value) from None
json.decoder.JSONDecodeError: Expecting value: line 1 column 1 (char 0)

Replace

r = requests.get('https://geocode.xyz/{},{}/json=1'.format(left_num,right_num))

with

r = requests.get('https://geocode.xyz/{},{}?json=1'.format(left_num,right_num))

Have a close look at the ? before json=1

/ was the issue here. If you look at the official documentation of the https://geocode.xyz/api , you will come to know about the issue.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM