title: Writing JSON preserving double backslashes
body: <p>I want to store python data structures as json on a Postgresql database.</p>
  
  <p>The <code>json.dumps()</code> works well and I get a properly formed JSON, as in:</p>
  
  <pre class="lang-py prettyprint-override"><code>&gt;&gt;&gt; import json
  &gt;&gt;&gt; j = { 'table': '"public"."client"' }
  &gt;&gt;&gt; json.dumps(j)
  '{"table": "\\"public\\".\\"client\\""}'
  </code></pre>
  
  <p>If I do <code>print(json.dumps(j))</code>, only one backslash is printed, since it is used by Python as an escape character, as in:</p>
  
  <pre class="lang-py prettyprint-override"><code>&gt;&gt;&gt; import json
  &gt;&gt;&gt; j = { 'table': '"public"."client"' }
  &gt;&gt;&gt; json.dumps(j)
  '{"table": "\\"public\\".\\"client\\""}'
  &gt;&gt;&gt; print(json.dumps(j))
  {"table": "\"public\".\"client\""}
  </code></pre>
  
  <h3>The problem</h3>
  
  <p>When I try to store this json on Postgresql with <code>psycopg2</code>, the <a href="http://initd.org/psycopg/docs/usage.html#values-containing-backslashes-and-like" rel="nofollow noreferrer">backslashes should not be stripped</a>, I think.</p>
  
  <pre class="lang-py prettyprint-override"><code>import psycopg2
  import json
  
  try:
      conn = psycopg2.connect("service=geotuga")
      cursor = conn.cursor()
      j = { 'table': '"public"."client"' }
      cursor.execute("INSERT INTO users.logger(subject,detail) VALUES (%s, %s);", ('json',json.dumps(j) ))
      conn.commit()
      cursor.close()
  except (Exception, psycopg2.Error) as e:
      print(e)
  finally:
      if conn is not None:
          conn.close()
  </code></pre>
  
  <p>On the database, the json string is stored as: <code>{"table": "\"public\".\"client\""}</code>. The double backslashes are gone.</p>
  
  <p><strong>How can I store the JSON properly created by <code>json.dumps</code> with <code>psycopg2</code> without loosing the double backslashes?</strong></p>
  
  <p>Note: The json stored on the database is no longer valid. If I try to parse it with Javascript, for example, it fails:</p>
  
  <pre><code>&gt; x = '{"table": "\"public\".\"client\""}'
  '{"table": ""public"."client""}'
  &gt; JSON.parse(x)
  SyntaxError: Unexpected token p in JSON at position 12
  </code></pre>