Skip to content

Commit 4caeb9c

Browse files
authored
Escape backslash characters when writing JSON (#707)
* JIRA WDT-437 - Escape backslash characters when writing JSON * JIRA WDT-437 - Revised comments
1 parent 8ef2643 commit 4caeb9c

File tree

1 file changed

+12
-8
lines changed

1 file changed

+12
-8
lines changed

core/src/main/python/wlsdeploy/json/json_translator.py

Lines changed: 12 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -169,7 +169,7 @@ def _write_dictionary_to_json_file(self, dictionary, writer, indent=''):
169169
for key, value in dictionary.iteritems():
170170
writer.println(end_line)
171171
end_line = ','
172-
writer.write(indent + '"' + _quote_embedded_quotes(key) + '" : ')
172+
writer.write(indent + '"' + _escape_text(key) + '" : ')
173173
if isinstance(value, dict):
174174
self._write_dictionary_to_json_file(value, writer, indent)
175175
elif isinstance(value, list):
@@ -230,19 +230,23 @@ def _format_json_value(value):
230230
if type(value) == bool or (isinstance(value, types.StringTypes) and (value == 'true' or value == 'false')):
231231
builder.append(JBoolean.toString(value))
232232
elif isinstance(value, types.StringTypes):
233-
builder.append('"').append(_quote_embedded_quotes(value.strip())).append('"')
233+
builder.append('"').append(_escape_text(value.strip())).append('"')
234234
else:
235235
builder.append(value)
236236
return builder.toString()
237237

238238

239-
def _quote_embedded_quotes(text):
239+
def _escape_text(text):
240240
"""
241-
Quote all embedded double quotes in a string with a backslash.
242-
:param text: the text to quote
243-
:return: the quotes result
241+
Escape the specified text for use in a double-quoted string.
242+
Escape embedded double quotes with a backslash.
243+
:param text: the text to escape
244+
:return: the escaped text
244245
"""
245246
result = text
246-
if isinstance(text, types.StringTypes) and '"' in text:
247-
result = text.replace('"', '\\"')
247+
if isinstance(text, types.StringTypes):
248+
if '\\' in text:
249+
result = text.replace('\\', '\\\\')
250+
if '"' in text:
251+
result = text.replace('"', '\\"')
248252
return result

0 commit comments

Comments
 (0)