1

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?

martineau
  • 119,623
  • 25
  • 170
  • 301
cjm2671
  • 18,348
  • 31
  • 102
  • 161
  • Does this answer your question? [Escape double quotes for JSON in Python](https://stackoverflow.com/questions/5997029/escape-double-quotes-for-json-in-python) – Tomerikoo Sep 06 '20 at 14:55
  • I tried it and got `{\"a\": \"b\"}`. Can you add a working example to see where we differ? – tdelaney Sep 06 '20 at 15:00
  • It seems weird to have to un-json the string to sign it. Shouldn't you be signing exactly what you send? – tdelaney Sep 06 '20 at 15:02

1 Answers1

6
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.

Or Y
  • 2,088
  • 3
  • 16