E.Lmo
E.Lmo

Reputation: 71

json.dumps doesn't work for me

I wrote a small Python script to get a response from GitHub and its GraphQL API.

Here is what I coded:

import json
def pp_json(json_thing, sort=True, indents=4):
    if type(json_thing) is str:
        print(json.dumps(json.loads(json_thing),sort_key=sort, indent=indents))
    else:
        print(json.dumps(json_thing, sort_key=sort, indent=indents))
    return None

I start this function with the output of my request as you can see here:

url = 'https://api.github.com/graphql'
json = { "query" : """query {
  viewer {
    login
    name
    bio
    company
    location
  }
}""" 
        }
api_token = "hiddencontent"
headers = {'Authorization': 'token %s' % api_token}

result_tokentest = requests.post(url=url, json=json, headers=headers) # just Response Code
string_tokentest = result_tokentest.text

print (result_tokentest)
print (string_tokentest)
pp_json(result_tokentest)

I get following output:

<Response [200]>
{"data":{"viewer":{"login":"datasienceelmo","name":"E.Lmo","bio":"Rohdaten sind geil!!","company":"Hochschule Ulm","location":"Ulm"}}}

--------------------------------------------------------------------------- AttributeError                            Traceback (most recent call last) <ipython-input-12-9c2eefbf15a2> in <module>()
     19 print (result_tokentest)
     20 print (string_tokentest)
---> 21 pp_json(result_tokentest)

<ipython-input-2-f2241ef62766> in pp_json(json_thing, sort, indents)
      4         print(json.dumps(json.loads(json_thing),sort_key=sort, indent=indents))
      5     else:
----> 6         print(json.dumps(json_thing, sort_key=sort, indent=indents))
      7     return None

AttributeError: 'dict' object has no attribute 'dumps'

I am unable to understand what the problem with my Python interpreter is, because I imported JSON. And in the documentation I just read how to use it, and I did as they did.

Upvotes: 2

Views: 1731

Answers (1)

Martijn Pieters
Martijn Pieters

Reputation: 1122372

You re-used the global name json for the module import and for a dictionary. The last assignment wins, so json now references the dictionary, not the module. Use a different name for the dictionary, like json_data:

json_data = { "query" : """query {
  viewer {
    login
    name
    bio
    company
    location
  }
}""" 

# ...

result_tokentest = requests.post(url=url, json=json_data, headers=headers)

Not that you need to use the json library at all here; the requests library supports decoding JSON responses natively by calling the response.json() method. You can pretty-print the result better by using the pprint library:

from pprint import pprint

pprint(result_tokentest.json())

As a side note: the GraphQL query itself is not JSON. There is no point in using the json library to parse or output a GraphQL query. It is fine to embed a GraphQL query in a JSON document however. The response is entirely in JSON.

Upvotes: 3

Related Questions