Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python3 remove newline character from json response

I am currently using the urllib to load a url request and then I load the response to json. This works perfectly but when I change the date range one field contains the \n character and is breaking the line.

How would I stop this from happening I have tried replace and rstrip but can't seem to get them to work.

Here is my code that extracts the data:

req = urllib.request.Request("http://example.com/file.json")

r = urllib.request.urlopen(req).read()
#r = r.rstrip('\n')
content = json.loads(r.decode('utf-8'))
#content.replace('\n','') - fails due to incorrect type

Thanks

like image 753
seanie_oc Avatar asked Oct 30 '25 11:10

seanie_oc


1 Answers

You try to call .replace on a dictionary. You should call .replace on the string:

content = json.loads(r.decode('utf-8').replace('\n', ''))

However, keep in mind that this may invalidate the string as json, depending on its content.

BTW, if you use requests you can get json directly:

import requests

content = requests.get("http://example.com/file.json").json()
like image 178
DeepSpace Avatar answered Nov 02 '25 01:11

DeepSpace



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!