Parsing JSON missing quotes on name
Is it possible to parse JSON when the name is m开发者_StackOverflow中文版issing double quotes? The JSON is coming from google and it's in the form of:
{e:"Data",b:"Data",f:"Data"}
I can't inform Google their JSON is invalid, because it's probably invalid for a reason for their proprietary system. When using json_decode() it returns NULL.
Is their any libraries that are able to parse JSON in this format?
JSON is a subset of YAML, so any valid JSON syntax is valid YAML syntax. YAML, however, doesn't require quotes around property names, so a YAML parser will cope with this content.
My preferred YAML parser is the Symfony YAML component, which you could use as follows:
<?php
include('yaml/lib/sfYaml.php');
var_dump(sfYaml::load('{e:"Data",b:"Data",f:"Data"}'));
Output:
array(3) {
["e"]=>
string(4) "Data"
["b"]=>
string(4) "Data"
["f"]=>
string(4) "Data"
}
// Serialize native Javascript object to JSON. To quote the key names. key=>'key'
function fix_json( $j ){
$j = trim( $j );
$j = ltrim( $j, '(' );
$j = rtrim( $j, ')' );
$a = preg_split('#(?<!\\\\)\"#', $j );
for( $i=0; $i < count( $a ); $i+=2 ){
$s = $a[$i];
$s = preg_replace('#([^\s\[\]\{\}\:\,]+):#', '"\1":', $s );
$a[$i] = $s;
}
//var_dump($a);
$j = implode( '"', $a );
//var_dump( $j );
return $j;
}
Example :
$json = '{e:"Data",b:"Data",f:"Data"}';
echo fix_json($json);
Output :
{"e":"Data","b":"Data","f":"Data"}
Indeed, this looks invalid. You might want to think about adding quotes using a piece of custom php code.
精彩评论