Escape double quotes when converting a dict to json in Python - python

I need to escape double quotes when converting a dict to json in Python, but I'm struggling to figure out how.
So if I have a dict like {'foo': 'bar'}, I'd like to convert it to json and escape the double quotes - so it looks something like:
'{\"foo\":\"bar\"}'
json.dumps doesn't do this, and I have tried something like:
json.dumps({'foo': 'bar'}).replace('"', '\\"') which ends up formatting like so:
'{\\"foo\\": \\"bar\\"}'
This seems like such a simple problem to solve but I'm really struggling with it.

Your last attempt json.dumps({'foo': 'bar'}).replace('"', '\\"') is actually correct for what you think you want.
The reason you see this:
'{\\"foo\\": \\"bar\\"}'
Is because you're printing the representation of the string. The string itself will have only a single backslash for each quote. If you use print() on that result, you will see a single backslash

What you have does work. Python is showing you the literal representation of it. If you save it to a variable and print it shows you what you're looking for.
>>> a = json.dumps({'foo': 'bar'}).replace('"', '\\"')
>>> print a
{\"foo\": \"bar\"}
>>> a
'{\\"foo\\": \\"bar\\"}'

Related

Converting backslash single quote \' to backslash double quote \" for JSON

I've got a JSON file that was converted to a string in Python. Somehow along the way the double quotes have gotten replaced with single quotes.
{\'MyJSON\': {\'Report\': \'1\' ....
I need to convert my string so that it is in this format instead:
{\"MyJSON\": {\"Report\": \"1\" ....
My problem is that using str.replace, I can't figure out how to convert a single quote into a double quote as both quotes are escaped.
My ultimate goal is to be able to put the string into json.loads so that I can pretty print it.
Attempts:
txt.replace(r"\'", r'\"')
> "{'MyJSON': {'Report': '1'"
txt.replace("\"", "\'")
> "{'MyJSON': {'Report': '1'"
If I save my string to a txt file it appears in the preview as:
{'MyJSON': {'Report': '1' ...
So I think what I actually need to do is replace ' with "
I have decided to use ast.literal_eval(txt) which can convert my string to a dictionary. From there, json.loads(json.dumps(dict)) gets me to JSON
i mean,
my_string = "\"\'"
print(my_string.replace("\'", "\""))
works perfectly fine
EDIT: i didn't mean use this directly, it was a proof of concept. In mine the replacement was reversed. I have updated this snippet such that it could directly be put into your code. Try it again
Instead of focusing on the backslashes to try to "hack" a json string / dict str into a JSON, a better solution is to take it one step at a time and start by converting my dict string into a dictionary.
import ast
txt = ast.literal_eval(txt) # convert my string to a dictionary
txt = json.loads(json.dumps(txt)) # convert my dict to JSON

Can't replace a string with multiple escape characters

I am having trouble with the replace() method. I want to replace some part of a string, and the part which I want to replace consist of multiple escape characters. It looks like something like this;
['<div class=\"content\">rn
To remove it, I have a block of code;
garbage_text = "[\'<div class=\\\"content\\\">rn "
entry = entry.replace(garbage_text,"")
However, it does not work. Anything is removed from my complete string. Can anybody point out where exactly I am thinking wrong about it? Thanks in advance.
Addition:
The complete string looks like this;
"['<div class=\"content\">rn gitar calmak icin kullanilan minik plastik garip nesne.rn </div>']"
You could use the triple quote format for your replacement string so that you don't have to bother with escaping at all:
garbage_text = """['<div class="content">rn """
Perhaps your 'entry' is not formatted correctly?
With an extra variable 'text', the following worked in Python 3.6.7:
>>> garbage_text
'[\'<div class=\\\'content\'\\">rn '
>>> text
'[\'<div class=\\\'content\'\\">rn And then there were none'
>>> entry = text.replace(garbage_text, "")
>>> entry
'And then there were none'

Python output a json style string

here defining a variable:
sms_param = '{\"website\":\"hello\"}'
and it print out ok like this : {"website":"hello"}, but i want to pass a dynamic value to its value, so its format should like this: {\"website\":\"{0}\"}.format(msg), but it output a KeyError, I have no idea of this Error, and change all kinds of string format such as triple quotation and change {0} with %s, but all seems useless. how can i solve it.
My suggestion is using json.loads()
>>> sms_param = '{\"website\":\"hello\"}'
>>> import json
>>> json.loads(sms_param)
{'website': 'hello'}
What you can do is using json.loads() convert the json string to dictionary and then change the value, finally convert it back to string

Python: replace &quote; to \"

I have a string like
This was really &quote;awesome&quote; isn't it?
And i need to convert the text to this format
This was really \"awesome\" isn't it?
I tried to use replace("&quote;", "\"") but I got this one:
This was really "awesome" isn\'t it?
Which is not exactly what I am trying to get.
Any idea?
Try using replace("&quote;", r'\"'). The r'...' with the "r" in front of the quotes means make it a "raw" string, so the backslashes are not interpreted as special characters (which is what happened to you in the first case).

Python str() - specify which kind of quotes to add/use?

Is there a way to influence the kind of quotes that python uses when casting a tuple/list to string?
For some NLP software I get tuples somewhat like this:
("It", ("isn't", "true"))
I want to cast it to a string and simply remove all double quotes and commas:
(It (Isn't true))
However, python is having its way with the quotes, it seems to prefer single quotes:
>>> print str(("It", ("Isn't" ,"true")))
('It', ("Isn't", 'true'))
, making my life more difficult. Of course I could write my own function for printing it out part-by-part, but there is so much similarity between the representation and native python tuples.
You can't rely on the exact representation that repr uses. I'd just do as you thought and write your own function -- I don't see it being more than a handful of lines of code. This should get you going.
def s_exp(x):
if isinstance(x, (tuple, list)):
return '(%s)' % (' '.join(map(s_exp, x)))
return str(x)
Writing your own function may be inevitable: if your strings contain brackets "(", ")" or spaces " " then you'll need some form of escaping to produce well-formed s-expressions.
Perhaps you can use json instead
>>> import json
>>> print json.dumps(("It", ("isn't", "true")))
["It", ["isn't", "true"]]
Python objects have a __str__ method that converts them into a string representation. This is what does the conversion and it's intelligent enough to use one kind of quote when the other is used in the string and also to do escaping if both are used.
In your example, the It got single quoted since that's what Python "prefers". The double quote was used for Isn't since it contains a `.
You should roll out your own converter really. Using a little recursion, it should be quite small.

Categories

Resources