Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to convert a dict to an escaped JSON string?

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?

like image 498
cjm2671 Avatar asked Jan 22 '26 06:01

cjm2671


2 Answers

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.

like image 95
Or Y Avatar answered Jan 24 '26 20:01

Or Y


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\"}"
like image 44
Zen3515 Avatar answered Jan 24 '26 18:01

Zen3515