Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Replace \b in json [duplicate]

Tags:

python

json

I'm receiving a json file that begins with : 'b\'{ "key" : .... I'm attempting to remove the 'b\' part of the string as it's not valid json.

The json is read using :

import urllib.request
link = "http://www...."
with urllib.request.urlopen(link) as url:
    s = str(url.read())

My code to replace is : replace('\'b\'', '') but the string 'b\'{ "key" : .... remains instead of { "key" : ....

Attempting to recreate the issue excluding the json string :

mystr = ' b\'{  '
mystr.replace(' b\'{ ', '') 

successfully replaces as ' ' is the output.

like image 973
blue-sky Avatar asked Mar 08 '26 04:03

blue-sky


1 Answers

You yourself are adding that b by calling str() on the data you get. Just don't do that.

If you do actually need to convert it to a string, you should decode it instead:

s = url.read().decode('utf-8')

but in fact you can almost certainly pass the bytestring directly to json.loads().

like image 61
Daniel Roseman Avatar answered Mar 09 '26 18:03

Daniel Roseman



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!