title: In Python, have json not escape a string
body: <p>I am caching some JSON data, and in storage it is represented as a JSON-encode string. No work is performed on the JSON by the server before sending it to the client, other than collation of multiple cached objects, like this:</p>
  
  <pre><code>def get_cached_items():
    item1 = cache.get(1)
    item2 = cache.get(2)
    return json.dumps(item1=item1, item2=item2, msg="123")
  </code></pre>
  
  <p>There may be other items included with the return value, in this case represented by <code>msg="123"</code>.</p>
  
  <p>The issue is that the cached items are double-escaped. It would behoove the library to allow a pass-through of the string without escaping it.</p>
  
  <p>I have looked at the documentation for <a href="http://docs.python.org/2/library/json.html#basic-usage" rel="noreferrer">json.dumps <code>default</code> argument</a>, as it seems to be the place where one would address this, and searched on google/SO but found no useful results.</p>
  
  <p>It would be unfortunate, from a performance perspective, if I had to decode the JSON of each cached items to send it to the browser. It would be unfortunate from a complexity perspective to not be able to use <code>json.dumps</code>.</p>
  
  <p>My inclination is to write a class that stores the cached string and when the <code>default</code> handler encounters an instance of this class it uses the string without perform escaping. I have yet to figure out how to achieve this though, and I would be grateful for thoughts and assistance.</p>
  
  <p><strong>EDIT</strong> For clarity, here is an example of the proposed <code>default</code> technique:</p>
  
  <pre><code>class RawJSON(object):
     def __init__(self, str):
         self.str = str
  
  class JSONEncoderWithRaw(json.JSONEncoder):
     def default(self, o):
         if isinstance(o, RawJSON): 
            return o.str # but avoid call to `encode_basestring` (or ASCII equiv.)
         return super(JSONEncoderWithRaw, self).default(o)
  </code></pre>
  
  <p>Here is a degenerate example of the above:</p>
  
  <pre><code>&gt;&gt;&gt; class M():
         str = ''
  &gt;&gt;&gt; m = M()
  &gt;&gt;&gt; m.str = json.dumps(dict(x=123))
  &gt;&gt;&gt; json.dumps(dict(a=m), default=lambda (o): o.str)
  '{"a": "{\\"x\\": 123}"}'
  </code></pre>
  
  <p>The desired output would include the unescaped string <code>m.str</code>, being:</p>
  
  <pre><code>'{"a": {"x": 123}}'
  </code></pre>
  
  <p>It would be good if the json module did not encode/escape the return of the <code>default</code> parameter, or if same could be avoided. In the absence of a method via the <code>default</code> parameter, one may have to achieve the objective here by overloading the <code>encode</code> and <code>iterencode</code> method of <code>JSONEncoder</code>, which brings challenges in terms of complexity, interoperability, and performance.</p>