import json import requests url = 'http://developer.usa.gov/1usagov.json' r = requests.get(url, stream=True) for line in r.iter_lines(): if line: print (json.loads(line))
Gives this error:
TypeError: can't use a string pattern on a bytes-like object
While viewing through the browser i do see that the response is a Json but request library says its a bytes like object why so ?
The Python "TypeError: cannot use a string pattern on a bytes-like object" occurs when we try to use a string pattern to match a bytes object. To solve the error, use the decode() method to decode the bytes object, e.g. my_bytes. decode('utf-8') .
If you want to replace a string that matches a regular expression (regex) instead of perfect match, use the sub() of the re module. In re. sub() , specify a regex pattern in the first argument, a new string in the second, and a string to be processed in the third.
If you use Python 3.x, you should pass str
object to json.loads
.
Replace following line:
print(json.loads(line))
with:
print(json.loads(line.decode()))
UPDATE: The behavior changed in Python 3.6. The argument can now be of type bytes or bytearray. The input encoding should be UTF-8, UTF-16 or UTF-32.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With