Consider a dict of the form:
myDict = {'a': 'b'}
If I do json.dumps(myDict), I get '{"a": "b"}'. So far so good.
What I'm trying to get is a string that looks like:
{\"a\":\"b\"} (in order to sign an API request).
I've tried doing .replace('"', '\\"'), which seemed to insert \\.
What am I doing wrong?
import json
myDict = {'a': 'b'}
print(json.dumps(myDict).replace('"', '\\"'))
Output:
{\"a\": \"b\"}
It works, it's just on the interpreter preview that it might seems to be double backslashed so you know that it is escaped.
My colleague suggest this to me, json can just dump you the string that you need
print(json.dumps(json.dumps(myDict)))
>>> import json
>>> myDict = {'a': 'b'}
>>> print(json.dumps(json.dumps(myDict)))
"{\"a\": \"b\"}"
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With