title: Extract an int, string, boolean, etc. as its corresponding PostgreSQL type from JSON
body: <p>I feel like I must just be missing something simple here, but I've looked through PostgreSQL's documentation on JSON and the JSON operators and functions and don't see anything explaining it.</p>
  
  <p>It's easy to turn things into JSON in PostgreSQL:</p>
  
  <pre><code>SELECT *, pg_typeof(j) FROM (VALUES
  (to_json(5)),
  (to_json(true)),
  (to_json('foo'::TEXT))
  ) x (j);
  </code></pre>
  
  <p>will give me back a nice result set full of <code>json</code>s:</p>
  
  <pre><code>   j   | pg_typeof
  -------+-----------
   5     | json
   true  | json
   "foo" | json
  </code></pre>
  
  <p>But how do I convert these <code>json</code> values <em>back</em> into their original types? I don't expect to be able to do that all in one result set, of course, since the types aren't consistent. I just mean individually.</p>
  
  <h1>Lots of stuff I tried</h1>
  
  <p>Casting sure doesn't work:</p>
  
  <pre><code>SELECT to_json(5)::NUMERIC;
  </code></pre>
  
  <p>gives</p>
  
  <pre><code>ERROR:  cannot cast type json to numeric
  </code></pre>
  
  <p>If I try to abuse the <code>json_populate_record</code> function like so:</p>
  
  <pre><code>SELECT json_populate_record(null::INTEGER, to_json(5));
  </code></pre>
  
  <p>I get</p>
  
  <pre><code>ERROR:  first argument of json_populate_record must be a row type
  </code></pre>
  
  <p>In PG 9.4, I can pretty easily tell the type: <code>SELECT json_typeof(to_json(5));</code> gives <code>number</code>, but that doesn't help me actually extract it.</p>
  
  <p>Neither does <code>json_to_record</code> (also 9.4):</p>
  
  <pre><code>SELECT * FROM json_to_record(to_json(5)) x (i INT);
  </code></pre>
  
  <p>gets me another error:</p>
  
  <pre><code>ERROR:  cannot call json_to_record on a scalar
  </code></pre>
  
  <p>So how do you convert <code>json</code> "scalars" (as PG calls them, apparently) into the corresponding PG type?</p>
  
  <p>I'm interested in 9.3 and 9.4; 9.2 would just be a bonus.</p>