title: Handling malformed JSON in PHP
body: <p>I'm trying to write a php script that handles data from a webservice that delivers "json" as a string. The problem is the string isn't really json; it's javascript. Specifically, the keys are not quoted, although the variables are. Example (the actual data is much longer and more complicated):</p>
  
  <pre><code>{desc:'User defined payload'}
  </code></pre>
  
  <p>As described by the <a href="http://www.php.net/manual/en/function.json-decode.php" rel="nofollow">php manual</a>, json_decode() correctly fails to interpret this string. </p>
  
  <p>My question is, how can I successfully interpret a string like this in php? </p>
  
  <p>The only solution I can think of is to write some regular expressions that fix the syntax, but then I'd have two problems.</p>
  
  <p>EDIT</p>
  
  <p>Hadvig's suggestion of using the Services_JSON pear module worked, and looks like a general solution. Once I had the module installed, my code looked like this:</p>
  
  <pre><code>require_once 'PEAR.php';
  require_once 'Services/JSON.php';
  
  $Services_JSON = new Services_JSON();
  $data = $Services_JSON-&gt;decode($malformed_json);
  </code></pre>
  
  <p>Unfortunately, this is SLOW. To interpret the whole string (~400,000 chars) took > 36 seconds! Using a regular expression to fix the quotes and then using json_decode took ~0.04 seconds. Here's what I used:</p>
  
  <pre><code>// fix single quotes
  $s = str_replace("'", '"', $malformed_json);
  
  // fix unquoted keys
  $valid_json = preg_replace('/([{\[,])\s*([a-zA-Z0-9_]+?):/', '$1"$2":', $s);
  
  $data = json_decode($valid_json);
  </code></pre>
  
  <p>Of course, this will break if the data contains any quotes, brackets, or commas.</p>