Actually it doesn't matter with escaped double quotes. See my test:
>>> json.loads['{"a": 1, "b": "{\"c\":2}"}']
Traceback [most recent call last]:
File "", line 1, in
File "/usr/lib/python3.4/json/__init__.py", line 318, in loads
return _default_decoder.decode[s]
File "/usr/lib/python3.4/json/decoder.py", line 343, in decode
obj, end = self.raw_decode[s, idx=_w[s, 0].end[]]
File "/usr/lib/python3.4/json/decoder.py", line 359, in raw_decode
obj, end = self.scan_once[s, idx]
ValueError: Expecting ',' delimiter: line 1 column 18 [char 17]
>>> json.loads['{"a": 1, "b": "{"c":2}"}']
Traceback [most recent call last]:
File "", line 1, in
File "/usr/lib/python3.4/json/__init__.py", line 318, in loads
return _default_decoder.decode[s]
File "/usr/lib/python3.4/json/decoder.py", line 343, in decode
obj, end = self.raw_decode[s, idx=_w[s, 0].end[]]
File "/usr/lib/python3.4/json/decoder.py", line 359, in raw_decode
obj, end = self.scan_once[s, idx]
ValueError: Expecting ',' delimiter: line 1 column 18 [char 17]
>>> json.loads['{"a": 1, "b": {"c":2}}']
{'a': 1, 'b': {'c': 2}}
>>> json.loads['{"a": 1, "b": {\"c\":2}}']
{'a': 1, 'b': {'c': 2}}
>>>
If you have a JSON formatted file, and you want to put it in the form of a string, with double quotes and newlines escaped, it’s a pain to do this manually. Note: if all you want to do is read in or print out JSON formatted text, then you can simply use the json library.
In my case I wanted to copy the JSON from an API guide, and automatically convert it to an escaped string.
The key
line to escape quotes and new lines is:
outstr = jsonstr.replace['"', '\\"'].replace['\n', '\\n']
If you need convert more than 2 characters there’s an interesting discussion about which is the most efficient method on Stackoverflow: Multiple character replace with python.
Here’s my Python script that takes a JSON file name as a command line argument and prints out the escaped string. It checks if the file exists, though doesn’t check that it is a valid JSON file..
# json2string.py - Python script to convert a formatted JSON file into a # string with escaped quotes and linefeeds for use in a REST call # # Usage: python json2string filename import sys import os.path def usage[]: sys.exit['Usage: python ' + sys.argv[0] + ' filename'] # check for single command argument if len[sys.argv] != 2: usage[] jsonfile = sys.argv[1] # check file exists if os.path.isfile[jsonfile] is False: print['File not found: ' + jsonfile] usage[] # get a file object and read it in as a string fileobj = open[jsonfile] jsonstr = fileobj.read[] fileobj.close[] # do character conversion here outstr = jsonstr.replace['"', '\\"'].replace['\n', '\\n'] # print the converted string print[outstr]
This entry was posted in Python and tagged Python. Bookmark the permalink.
Hi, I have this json and I can't manage to escape the double quotes
I've seen great answers in this subreddit about similar cases but none of them work.
//regex101.com/r/ifV8hX/3
Thanks!
{
"@context": "
//schema.org/
",
"@type": "Product",
"image":["
//
reevo.com/tv56"],
"description": "Smart TV 56" + 3d",
"sku": "1805829",
"brand": {
"@type": "Thing",
"name": "Samsung"
},
"offers": {
"@type": "Offer",
"priceCurrency": "USD",
"availability": "
//schema.org/OutOfStock
",
"seller": {
"@type": "Organization",
"name": "Reevo"
},
"price": "599.00"
},
"name": "Smart TV 56" + 3d"
}
Comments
BorisPolonsky changed the title Single quotes [i.e. "'"] escaped wthin string for JSON leads to malformed resposne in REST API Single quotes escaped wthin string for JSON leads to malformed JSON responses in REST API
Apr 16, 2020BorisPolonsky changed the title Single quotes escaped wthin string for JSON leads to malformed JSON responses in REST API Single quotes escaped wthin string leads to malformed JSON responses in REST API
Apr 16, 2020BorisPolonsky changed the title Single quotes escaped wthin string leads to malformed JSON responses in REST API [Bug] Single quotes escaped wthin string leads to malformed JSON responses in REST API
Apr 16, 2020netfs added a commit to netfs/serving that referenced this issue
May 18, 2020
prevent malformed JSON responses that fail to parse.
Fixes tensorflow#1600
PiperOrigin-RevId: 310921928
[cherry picked from commit e1ceccb]