1

I have searched for a solution regarding this issue and I have not found one that I can understand. I am new to Python and need basic help understanding why I get the error message: TypeError: is not JSON serializable.

import requests
import json

r = requests.get("http://api.bls.gov/publicAPI/v2/timeseries/data/LAUCN040010000000005")

with open("C:\...MyPath...\Output.txt", "w") as outfile:
    json.dumps(r, outfile)

This is my simple code I am testing. I appreciate the help.

2
  • r is not a JSON object; you can't dumps something that isn't json. You can, however, first parse the bls string to a JSON object and then dumps it. I don't see much sense in that, though. Commented Jun 27, 2016 at 19:29
  • you need to also indent your json.dumps in the with block Commented Jun 27, 2016 at 19:30

2 Answers 2

2

You don't need to convert it to/from json. Just keep it as text.

import requests

r = requests.get("http://api.bls.gov/publicAPI/v2/timeseries/data/LAUCN040010000000005")

with open("C:\Users\mhoward2\Documents\Python Scripts\Output.txt", "w") as outfile:
    outfile.write(r.text)
Sign up to request clarification or add additional context in comments.

2 Comments

Thank you very much> I now have some JSON on my hard drive. I have learned so much from stackoverflow over the years...VBA...SQL...and now Python. This is the first question I have ever had to ask.
glad I could help :)
1

You need to call .json() and dump or just write the content:

r = requests.get("http://api.bls.gov/publicAPI/v2/timeseries/data/LAUCN040010000000005")

with open("C:\Users\mhoward2\Documents\Python Scripts\Output.txt", "w") as outfile:
     outfile.write(r.content)

What you are trying to write currently is:

 <Response [200]>

which is a requests.models.Response object.

4 Comments

content lets you access the response as bytes, so the call to open should probably have wb instead of just w
@iliacholy, not in python2.
What do you mean? (not saying you're wrong, just curious)
bytes is an alias for str in python2, type(r.content) -> str, in general you should use .content with requests and let it handle the encoding. Python 3 is obviously a different story

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.