Dictionary encoded Python

0

I need to convert A to B. I work with Python 2.7

A:

payload = {"trafficChannel":{"name":"tuviaasa","status":0,"billedEvent":"ai","env":"desktop","dealType":"fixed_price","optimizeAllAdSources":"false","optimizeFor":"ecpm","publisher":"5a031c0b909cad0002b76ee2"}}

B:

payload = "{\"trafficChannel\":{\"name\":\"tuviaasa\",\"status\":0,\"billedEvent\":\"ai\",\"env\":\"desktop\",\"dealType\":\"fixed_price\",\"optimizeAllAdSources\":false,\"optimizeFor\":\"ecpm\",\"publisher\":\"5a031c0b909cad0002b76ee2\"}}"
    
asked by Martin Bouhier 08.11.2017 в 21:21
source

2 answers

1

Martín is very simple

payload = {"trafficChannel":{"name":"tuviaasa","status":0,"billedEvent":"ai","env":"desktop","dealType":"fixed_price","optimizeAllAdSources":"false","optimizeFor":"ecpm","publisher":"5a031c0b909cad0002b76ee2"}}

new_payload = str(payload).replace("'","\\"")
print(new_payload)

Exit:

{\"trafficChannel\": {\"name\": \"tuviaasa\", \"status\": 0, \"billedEvent\": \"ai\", \"env\": \"desktop\", \"dealType\": \"fixed_price\", \"optimizeAllAdSources\": \"false\", \"optimizeFor\": \"ecpm\", \"publisher\": \"5a031c0b909cad0002b76ee2\"}}

We use str to generate the dictionary representation as a string. Finally, we replace the single quotes with \"

    
answered by 08.11.2017 / 22:22
source
1

You can do it using the library json :

>>> payload
{'trafficChannel': {'status': 0, 'publisher': '5a031c0b909cad0002b76ee2', 'name': 'tuviaasa', 'env': 'desktop', 'optimizeFor': 'ecpm', 'dealType': 'fixed_price', 'optimizeAllAdSources': 'false', 'billedEvent': 'ai'}}
>>> type(payload)
<type 'dict'>
>>> import json
>>> nuevo_payload = json.dumps(payload)
>>> nuevo_payload
'{"trafficChannel": {"status": 0, "publisher": "5a031c0b909cad0002b76ee2", "name": "tuviaasa", "env": "desktop", "optimizeFor": "ecpm", "dealType": "fixed_price", "optimizeAllAdSources": "false", "billedEvent": "ai"}}'
>>> type(nuevo_payload)
<type 'str'>

What json.dumps does is serialize the dictionary to JSON text format .

    
answered by 08.11.2017 в 22:57