I'd like to replace a dictionary in a dictionary, but when I try I keep getting quotes and slashes around the added dictionary.
current_dict = {"header": {"from": "/app/off_grid_control/subscribe",
"messageId": "ef6b8e50620ac768569f1f7abc6507a5", "method": "SET",
"namespace": "Appliance.Control.ToggleX", "payloadVersion": 1,
"sign": "e48c24e510044d7e2d248c68ff2c10ca", "timestamp": 1601908439,
"triggerSrc": "Android"}, "payload": {"togglex": {"channel": 0, "onoff": 1}}}
raw_payload = {"togglex": {"channel": 0, "onoff": 1}}
payload = json.dumps(raw_payload)
From a print statement I get:
payload = {"togglex": {"channel": 0, "onoff": 0}}
So that looks fine.
Then I try and add the new dictionary part into the original dictionary:
current_dict["payload"] = payload
And get this:
current_dict = {"header": {"from": "/app/off_grid_control/subscribe",
"messageId": "ef6b8e50620ac768569f1f7abc6507a5", "method": "SET",
"namespace": "Appliance.Control.ToggleX", "payloadVersion": 1,
"sign": "e48c24e510044d7e2d248c68ff2c10ca", "timestamp": 1601908439,
"triggerSrc": "Android"}, "payload": "{\"togglex\": {\"channel\": 0, \"onoff\": 0}}"}
Noting all the added "
and \
around the payload values.
Can someone please help with out to add a different dictionary to "payload" cleanly?
CodePudding user response:
when you do:
payload = json.dumps(raw_payload)
you're converting your dict to a json string that only looks like a dictionary. if you want to add it to an outer dict as a python object, you need to to do it like this:
current_dict["payload"] = json.loads(payload)