Passing a Python string into JSON payload

12,304

Solution 1

'+ targetTemp +' within the outermost double quotes isn't doing string concatenation. It's literally putting that text.

You should be using "+ targetTemp +"

However, building an actual dictionary, and using json.dumps will be less error-prone

Solution 2

The reason your string isn't working is because you used double quotes " for the string instead of single quotes '. Since json format requires double quotes, you only should be using double quotes inside the string itself and then use the single quotes to denote the start/end of a string. (That way you don't need to keep using those \" unnecessarily.
Also, .format() can help with putting variables inside strings to make them easier.

This should fix your json string:

targetTemp = 17

payload = '{\n    "nodes": [{\n        "attributes": {\n            "targetHeatTemperature": {\n                "targetValue": {},\n            }\n        }\n    }]\n}'.format(targetTemp)

However, using the json module makes things a lot easier because it allows you to pass in a python dictionary which can be converted from/to a json string.

Example using the json package:

import json

targetTemp = 17

payload = {
    "nodes": [{
        "attributes": {
            "targetHeatTemperature": {
                "targetValue": targetTemp
            }
        }
    }]
}

payload_json = json.dumps(payload)  # Convert dict to json string

Solution 3

Your payload is awfully complex, you don't need to enclose it in quotes since it can be treated as a dict, also your targetTemp is being treated as a string this is why you don't see the actual value.

You may need to look into Python string formatting for simplicity.

This would do what you want,

import json

targetTemp = 17
payload = {
    "nodes": [{
        "attributes": {
            "targetHeatTemperature": {
                "targetValue": targetTemp
            }
        }
    }]
}

print(json.dumps(payload))

# output,
{"nodes": [{"attributes": {"targetHeatTemperature": {"targetValue": 17}}}]}

Please note that you can also use JSON Validators to make sure your json object is indeed in a correct format.(that's what I used to format your provided JSON)

Solution 4

Let's shorten that code down a bit.

payload = "{...\"targetValue\": '+ targetTemp +'...}"

See the problem now? payload is delimited with double quotes, so in order to exit, append to, and "re-enter" the string, you need to use double quotes instead of single quotes:

payload = "{...\"targetValue\": "+ targetTemp +"...}"

Alternatively, the far more robust and less tedious solution would be to build up payload as a dict of Python structures containing targetTemp as a normal value, and then after that serialize it with json.dumps:

payload_obj = {
    "nodes": [{
         "attributes": {
             "targetHeatTemperature": {
                 "targetValue": targetTemp,
             }
         }
    }]
}

payload = json.dumps(payload_obj)
Share:
12,304
AndyJ
Author by

AndyJ

Updated on July 14, 2022

Comments

  • AndyJ
    AndyJ almost 2 years

    I have this in my code:

    targetTemp = 17
    ...
    payload = "{\n    \"nodes\": [{\n        \"attributes\": {\n            \"targetHeatTemperature\": {\n                \"targetValue\": '+ targetTemp +',\n            }\n        }\n    }]\n}"
    

    I've tried a few things I've found online but nothing seems to work. If I replace '+ targetTemp +', with, say, 18 then it does what I want.

    I've tried just with single quotes and no plus signs, just the variable name, without the comma at the end. I'm just stumbling round in the dark, really.

    • anthony sottile
      anthony sottile over 5 years
      json.dumps is probably what you want to use instead of manually building json strings
  • OneCricketeer
    OneCricketeer over 5 years
    Why format instead of put the value directly? Or even str(targetTemp)?
  • AndyJ
    AndyJ over 5 years
    I use Postman to get my API call right and then export it from there. This is my first Python/Flask/JSON project. I might have bitten off more than I can chew but most things are working.
  • Sufiyan Ghori
    Sufiyan Ghori over 5 years
    make sense @AndyJ, hope my answer helped you
  • AndyJ
    AndyJ over 5 years
    That got me there after a fashion. I actually get the value from a MySQL table so it's targetTemp = data[0]. I then had to add targetTemp=str(targetTemp) as I was getting a server error. Thank you though, this got me where I want to be