]> granicus.if.org Git - python/commitdiff
#18958: Improve error message for json.load(s) while passing a string that starts...
authorEzio Melotti <ezio.melotti@gmail.com>
Sun, 20 Oct 2013 23:10:55 +0000 (02:10 +0300)
committerEzio Melotti <ezio.melotti@gmail.com>
Sun, 20 Oct 2013 23:10:55 +0000 (02:10 +0300)
Lib/json/__init__.py
Lib/test/test_json/test_decode.py
Misc/NEWS

index 6cedb6e31f7c8cc5374b5a65f6e1bfe1e58a633f..a459f77a7b4d035fdd9dd3b3ed12218ef72be490 100644 (file)
@@ -313,6 +313,8 @@ def loads(s, encoding=None, cls=None, object_hook=None, parse_float=None,
     if not isinstance(s, str):
         raise TypeError('the JSON object must be str, not {!r}'.format(
                             s.__class__.__name__))
+    if s.startswith(u'\ufeff'):
+        raise ValueError("Unexpected UTF-8 BOM (decode using utf-8-sig)")
     if (cls is None and object_hook is None and
             parse_int is None and parse_float is None and
             parse_constant is None and object_pairs_hook is None and not kw):
index 05d07b72190071b9722b8a08493be8fed7175065..35c02de88cc6e4f7bf8375ef8d8e5a2f69bcf2c2 100644 (file)
@@ -77,5 +77,19 @@ class TestDecode:
         with self.assertRaisesRegex(TypeError, msg):
             self.json.load(BytesIO(b'[1,2,3]'))
 
+    def test_string_with_utf8_bom(self):
+        # see #18958
+        bom_json = "[1,2,3]".encode('utf-8-sig').decode('utf-8')
+        with self.assertRaises(ValueError) as cm:
+            self.loads(bom_json)
+        self.assertIn('BOM', str(cm.exception))
+        with self.assertRaises(ValueError) as cm:
+            self.json.load(StringIO(bom_json))
+        self.assertIn('BOM', str(cm.exception))
+        # make sure that the BOM is not detected in the middle of a string
+        bom_in_str = '"{}"'.format(''.encode('utf-8-sig').decode('utf-8'))
+        self.assertEqual(self.loads(bom_in_str), '\ufeff')
+        self.assertEqual(self.json.load(StringIO(bom_in_str)), '\ufeff')
+
 class TestPyDecode(TestDecode, PyTest): pass
 class TestCDecode(TestDecode, CTest): pass
index bff7097a60c6ad3083387f5f5c7b1bf02273786b..af66063d69da3fddab041c85032b15ae8bf42eb0 100644 (file)
--- a/Misc/NEWS
+++ b/Misc/NEWS
@@ -62,6 +62,9 @@ Core and Builtins
 Library
 -------
 
+- Issue #18958: Improve error message for json.load(s) while passing a string
+  that starts with a UTF-8 BOM.
+
 - Issue #19307: Improve error message for json.load(s) while passing objects
   of the wrong type.