4

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

1
  • What do you mean by "when I change the date range", and who is producing this json ? (if it's you then fix the problem at the source instead, if it's not you and the json is invalid then contact the site's admins/maintainer and ask them to fix it) Commented Oct 18, 2018 at 11:25

3 Answers 3

4

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()
Sign up to request clarification or add additional context in comments.

1 Comment

Hi, I tried to add the .replace it ran but didn't remove the \n
0

json.loads accepts an argument indents which will indent each line in the JSON. Setting the argument to None removes new line breaks.

You can try:

json.dumps(indents=None)

Comments

-1

Try the python String method

json.loads(str(r,”utf-8”))

To replace string only

New_str = str(r,”utf-8”)

3 Comments

Hi I change the following: content = json.loads(str(r,'utf-8')) and added cont.replace('\n','') When I ran the code I got an error saying replace could not be preformed on a dict
I think after executed json.loads it will convert the response to dict format that’s why it can not replace because replace is a string function.
Hi, I'm not having any luck with the solution provided.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.