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.
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