0

I have some code that calls an API with JSON data and the Requests library in Python, it works well when the JSON strings are hard coded. When the JSON data needs to be dynamic I decided to go with dumping a python object to JSON via json.dumps() as follows:

def testJSON(testVar):   #set testVar = 22.22

    data = {}
    data['Key1'] = 'Value1'
    data['Key2'] = 'Value2'
    data['Key3'] = str(testVar)
    params = json.dumps(data)
    print params
    params2 = {"Key1":"Value1","Key2":"Value2","Key3":"22.22"}
    print params2

when I run this from the command line the output is as follows:

{"Key1":"Value1","Key2":"Value2","Key3":"22.22"}
{'Key1':'Value1','Key2':'Value2','Key3':'22.22'}

The hard coded JSON string params2 works as expected in an API call but the object dumped to JSON with json.dumps() doesn't. The output of both these methods look the same except for single and double quotes, which shouldn't matter, right?

Cœur
  • 37,241
  • 25
  • 195
  • 267
haliax
  • 1
  • 1
  • 1
    I'm not sure exactly what you're asking. `params` is a JSON string. `params2` is a Python object. Of course when your `print` that the Python string-ificiation looks different from the JSON. They are two different things. – larsks Sep 04 '17 at 21:03
  • 2
    Show us the api call – George Daramouskas Sep 04 '17 at 21:09
  • 1
    `params2` is **not a JSON string**. It is a `dict`, and you are printing a string representation of your Python `dict`, but that is *not valid JSON*. What, *exactly* are you doing that you API call doesn't work? – juanpa.arrivillaga Sep 04 '17 at 21:12

0 Answers0