Home > other >  How do I use variables inside a stringified key in a nested dict?
How do I use variables inside a stringified key in a nested dict?

Time:04-07

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)

CodePudding user response:

You can use python inbuilt json module to serialize and deserialize json objects. You example is a dict with serialized nested text 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

import json

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"
}

text_obj = json.loads(msg_body["Command"]["text"])

then we update values like you mentioned

text_obj["2"]["22"] = "serial_val" # was "Serial" before
text_obj["2"][<other_key>] = <other value>

then we serialize the text_obj and update value in msg_body

msg_body["Command"]["text"] = json.dumps(text_obj)
print(msg_body)

now you can use msg_body with updated value to make web request.

  • Related