如何在嵌套字典的字符串化键内使用变量?
我有一个默认消息主体,该消息将用于作为邮政请求发送。 以下是我的消息主体: -
msg_body = {
"deviceId": "36330586",
"Command": {
"text": "{\"2\":{\"21\":\"agenda\",\"22\":\"Serial\",\"31\":\"On\",\"32\":\"On\",\"33\":\"Off\",\"34\":\"Off\",\"41\":\"127\",\"51\":\"0:21\",\"61\":\"5:21\",\"71\":\"10\",\"81\":\"10\",\"91\":\"0\",\"101\":\"0\",\"111\":\"false\"}}"
},
"description": "Execute command 2"
}
我正在调用一个API来获取我需要使用text
中的变量传递的值。 例如,文本
包含键21 22 31 32
等等。这样我就可以传递我从API获得的值。 因此:例如:
\"21\":\"agenda\",\"22\":\"Serial\",\"31\":\"On\"....
我想使用变量模式,而不是议程,对于序列号,我想使用变量serial_val等传递该值,依此类推...
然后将使用此消息主体来提出发布请求:
r2 = requests.post(url, data=json.dumps(msg_body), headers=headers)
I have a default message body which is to be used to send as a post request.
Below is my message body : -
msg_body = {
"deviceId": "36330586",
"Command": {
"text": "{\"2\":{\"21\":\"agenda\",\"22\":\"Serial\",\"31\":\"On\",\"32\":\"On\",\"33\":\"Off\",\"34\":\"Off\",\"41\":\"127\",\"51\":\"0:21\",\"61\":\"5:21\",\"71\":\"10\",\"81\":\"10\",\"91\":\"0\",\"101\":\"0\",\"111\":\"false\"}}"
},
"description": "Execute command 2"
}
I'm calling an api to fetch the values which I need to pass using variables inside text
.
For example the text
contains keys 21 22 31 32
and so on.... I want to use variables for each of the values in text
so that I can pass the values which I get from the api.
Therefore for example :
\"21\":\"agenda\",\"22\":\"Serial\",\"31\":\"On\"....
Instead of agenda I want to use a variable mode, for Serial I want to pass the value using variable serial_val and so on...
This message body will be then used for making post request :
r2 = requests.post(url, data=json.dumps(msg_body), headers=headers)
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

您可以使用python in Innoled
JSON
模块来序列化和挑选JSON对象。您的示例是一个带有序列化的嵌套文本
键的dict,您可以对其进行反序列化并转换为JSON对象。首先,我们应该对文本部分进行审理,因为这似乎是您最重要的部分
,然后我们像您提到的那样更新值
,然后我们序列化
text_obj
并在msg_body
中更新值可以使用带有更新值的
msg_body
来制作Web请求。You can use python inbuilt
json
module to serialize and deserialize json objects. You example is a dict with serialized nestedtext
key which you can deserialize and convert to json object.First we deserialize the text part because that seems to be the most important part for you
then we update values like you mentioned
then we serialize the
text_obj
and update value inmsg_body
now you can use
msg_body
with updated value to make web request.