Use JSONEncoder to escape JSON strings.
This CL fixes escaping of '\n' and unicode characters.
BUG=grit-i18n:20
Landing for alexeypa@chromium.org, patch from issue 18301005.
Review URL: https://codereview.chromium.org/18860003
git-svn-id: http://grit-i18n.googlecode.com/svn/trunk@129 7262f16d-afe8-6277-6482-052fa10e57b1
diff --git a/grit/format/chrome_messages_json.py b/grit/format/chrome_messages_json.py
index 5609122..7b370d7 100644
--- a/grit/format/chrome_messages_json.py
+++ b/grit/format/chrome_messages_json.py
@@ -6,6 +6,7 @@
"""Formats as a .json file that can be used to localize Google Chrome
extensions."""
+from json import JSONEncoder
import re
import types
@@ -16,20 +17,19 @@
"""Format the messages as JSON."""
yield '{\n'
+ encoder = JSONEncoder();
format = (' "%s": {\n'
- ' "message": "%s"\n'
+ ' "message": %s\n'
' }')
first = True
for child in root.ActiveDescendants():
if isinstance(child, message.MessageNode):
- loc_message = child.Translate(lang)
- loc_message = re.sub(r'\\', r'\\\\', loc_message)
- loc_message = re.sub(r'"', r'\"', loc_message)
-
id = child.attrs['name']
if id.startswith('IDR_'):
id = id[4:]
+ loc_message = encoder.encode(child.Translate(lang))
+
if not first:
yield ',\n'
first = False
diff --git a/grit/format/chrome_messages_json_unittest.py b/grit/format/chrome_messages_json_unittest.py
index 8cbd672..484230f 100644
--- a/grit/format/chrome_messages_json_unittest.py
+++ b/grit/format/chrome_messages_json_unittest.py
@@ -53,7 +53,7 @@
"message": "Simple message."
},
"IDS_QUOTES": {
- "message": "element\u2019s \u201c%s\u201d attribute"
+ "message": "element\\u2019s \\u201c%s\\u201d attribute"
},
"IDS_PLACEHOLDERS": {
"message": "%1$d error, %2$d warning"
@@ -86,10 +86,10 @@
test = u"""
{
"ID_HELLO": {
- "message": "H\xe9P\xe9ll\xf4P\xf4!"
+ "message": "H\\u00e9P\\u00e9ll\\u00f4P\\u00f4!"
},
"ID_HELLO_USER": {
- "message": "H\xe9P\xe9ll\xf4P\xf4 %s"
+ "message": "H\\u00e9P\\u00e9ll\\u00f4P\\u00f4 %s"
}
}
"""