[英]Passing a Python string into JSON payload
我的代码中有这个:
targetTemp = 17
...
payload = "{\n \"nodes\": [{\n \"attributes\": {\n \"targetHeatTemperature\": {\n \"targetValue\": '+ targetTemp +',\n }\n }\n }]\n}"
我尝试了一些我在网上找到的东西,但似乎没什么用。 如果我用'+ targetTemp +'替换,比方说18,那么它就能满足我的需求。
我只尝试过单引号而没有加号,只是变量名,最后没有逗号。 我真的只是在黑暗中磕磕绊绊。
最外面的双引号内的'+ targetTemp +'
没有进行字符串连接。 它确实放了那个文字。
你应该使用"+ targetTemp +"
但是,构建一个实际的字典,并使用json.dumps
将不那么容易出错
你的字符串不工作的原因是因为你使用双引号"
为字符串而不是单引号'
。由于json格式需要双引号,你只应在字符串本身内使用双引号然后使用单引号表示字符串的开始/结束。(这样你就不需要使用那些保持\\"
不必要的。
此外, .format()
可以帮助将变量放在字符串中以使它们更容易。
这应该修复你的json字符串:
targetTemp = 17
payload = '{\n "nodes": [{\n "attributes": {\n "targetHeatTemperature": {\n "targetValue": {},\n }\n }\n }]\n}'.format(targetTemp)
但是,使用json
模块会使事情变得更容易,因为它允许您传入一个python字典,该字典可以从/转换为json字符串。
使用json
包的示例:
import json
targetTemp = 17
payload = {
"nodes": [{
"attributes": {
"targetHeatTemperature": {
"targetValue": targetTemp
}
}
}]
}
payload_json = json.dumps(payload) # Convert dict to json string
你的payload
非常复杂,你不需要将它括在引号中,因为它可以被视为一个dict
,你的targetTemp
也被视为一个字符串,这就是你没有看到实际值的原因。
为简单起见,您可能需要查看Python字符串格式 。
这会做你想要的,
import json
targetTemp = 17
payload = {
"nodes": [{
"attributes": {
"targetHeatTemperature": {
"targetValue": targetTemp
}
}
}]
}
print(json.dumps(payload))
# output,
{"nodes": [{"attributes": {"targetHeatTemperature": {"targetValue": 17}}}]}
请注意,您还可以使用JSON Validators来确保您的json对象确实格式正确。(这就是我用来格式化您提供的JSON
)
让我们将代码缩短一点。
payload = "{...\"targetValue\": '+ targetTemp +'...}"
现在看到问题? payload
用双引号分隔,因此为了退出,追加和“重新输入”字符串,你需要使用双引号而不是单引号:
payload = "{...\"targetValue\": "+ targetTemp +"...}"
或者,更强大,更乏味的解决方案是将payload
构建为包含targetTemp
作为普通值的Python结构的dict
, 然后用json.dumps
序列化它:
payload_obj = {
"nodes": [{
"attributes": {
"targetHeatTemperature": {
"targetValue": targetTemp,
}
}
}]
}
payload = json.dumps(payload_obj)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.