Search code examples
pythonjsonvariablespayload

Passing a Python string into JSON payload


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.


Solution

  • '+ 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