Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

TypeError: can't use a string pattern on a bytes-like object

Tags:

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 ?

like image 436
user3249433 Avatar asked Jan 29 '14 15:01

user3249433


People also ask

How do you fix Cannot use string pattern on a bytes like object?

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') .

How do you're sub in Python?

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.


1 Answers

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.

like image 110
falsetru Avatar answered Oct 16 '22 06:10

falsetru