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
  • 112,593
  • 23
  • 157
  • 280
cjm2671
  • 16,836
  • 28
  • 92
  • 144
  • 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

4
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
  • 1,923
  • 1
  • 15