0

I got some data from an API with Python, and I'm trying to print it to a file. My understanding was that the indent argument lets you pretty print. Here's my code:

import urllib2, json

APIKEY_VALUE = "APIKEY"
APIKEY = "?hapikey=" + APIKEY_VALUE
HS_API_URL = "http://api.hubapi.com"

def getInfo():

    xulr = "/engagements/v1/engagements/paged"

    url = HS_API_URL + xulr + APIKEY + params
    response = urllib2.urlopen(url).read()

    with open("hubdataJS.json", "w") as outfile:
        json.dump(response, outfile, sort_keys=True, indent=4, ensure_ascii=False)

getInfo()

What I expected hubdataJS.json to look like when I opened it in Sublime text is some JSON with a format like this:

{
    a: some data
    b: [
        some list of data,
        more data
    ]
    c: some other data
}

What I got instead was all the data on one line, in quotes (I thought dumps was for outputting as a string), with lots of \s, \rs, and \ns.

Confused about what I'm doing wrong.

0

1 Answer 1

4

in your code, response is a bytestring that contains the data serialized in the json format. When you do json.dump you're serializing the string to json. You end up with a json formatted file containing a string, and in that string you have another json data, so, json inside json.

To solve that you have to decode (deserialize) the bytestring data you got from the internet, before reencoding it to json to write in the file.

response = json.load(urllib2.urlopen(url))

that will convert the serialized data from the web into a real python object.

Sign up to request clarification or add additional context in comments.

1 Comment

That did it! Thank you.

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.