#12017: merge with 3.1.
diff --git a/Lib/test/json_tests/test_recursion.py b/Lib/test/json_tests/test_recursion.py
index 1e9b8ab..6d5db50 100644
--- a/Lib/test/json_tests/test_recursion.py
+++ b/Lib/test/json_tests/test_recursion.py
@@ -65,3 +65,15 @@
             pass
         else:
             self.fail("didn't raise ValueError on default recursion")
+
+
+    def test_highly_nested_objects(self):
+        # test that loading highly-nested objects doesn't segfault when C
+        # accelerations are used. See #12017
+        with self.assertRaises(RuntimeError):
+            json.loads('{"a":' * 100000 + '1' + '}' * 100000)
+        with self.assertRaises(RuntimeError):
+            json.loads('{"a":' * 100000 + '[1]' + '}' * 100000)
+        with self.assertRaises(RuntimeError):
+            json.loads('[' * 100000 + '1' + ']' * 100000)
+
diff --git a/Misc/NEWS b/Misc/NEWS
index 1f48a14..da4a46c 100644
--- a/Misc/NEWS
+++ b/Misc/NEWS
@@ -324,8 +324,11 @@
 
 - Issue #11179: Make ccbench work under Python 3.1 and 2.7 again.
 
-Extensions
-----------
+Extension Modules
+-----------------
+
+- Issue #12017: Fix segfault in json.loads() while decoding highly-nested
+  objects using the C accelerations.
 
 - Issue #1838: Prevent segfault in ctypes, when _as_parameter_ on a class is set
   to an instance of the class.
diff --git a/Modules/_json.c b/Modules/_json.c
index 75b14ee..dd71003 100644
--- a/Modules/_json.c
+++ b/Modules/_json.c
@@ -927,6 +927,7 @@
 
     Returns a new PyObject representation of the term.
     */
+    PyObject *res;
     Py_UNICODE *str = PyUnicode_AS_UNICODE(pystr);
     Py_ssize_t length = PyUnicode_GET_SIZE(pystr);
     if (idx >= length) {
@@ -941,10 +942,20 @@
                 next_idx_ptr);
         case '{':
             /* object */
-            return _parse_object_unicode(s, pystr, idx + 1, next_idx_ptr);
+            if (Py_EnterRecursiveCall(" while decoding a JSON object "
+                                      "from a unicode string"))
+                return NULL;
+            res = _parse_object_unicode(s, pystr, idx + 1, next_idx_ptr);
+            Py_LeaveRecursiveCall();
+            return res;
         case '[':
             /* array */
-            return _parse_array_unicode(s, pystr, idx + 1, next_idx_ptr);
+            if (Py_EnterRecursiveCall(" while decoding a JSON array "
+                                      "from a unicode string"))
+                return NULL;
+            res = _parse_array_unicode(s, pystr, idx + 1, next_idx_ptr);
+            Py_LeaveRecursiveCall();
+            return res;
         case 'n':
             /* null */
             if ((idx + 3 < length) && str[idx + 1] == 'u' && str[idx + 2] == 'l' && str[idx + 3] == 'l') {