I've a got this string after parsing webpage. It looks something similar to this, which is not a valid format of JSON. I was wondering if I can parse this string to get desired values.
string(4747) " _result_ ={status:"OK",loc:"India",
country:{regions:[{ap:"755",mp:"768"},{up:"125",mh:"188"}]},src:"gov"}"
Here you can observe that, the fieldNames doesn't have quotes at all. I've tried to json_decode() which returned NULL. So, Please help me in parsing this string. Thank you.
The field names don't need to have quotes if they are just single-word strings. The problem is likely right at the beginning:
" _result_ ="
That's the problem. Try str_replace(' _result_ =', '', $string);
and see if it will decode then.
It looks like you can simply remove any portion of the string up to the first {
$raw_string = '...'; // your string to cleanse
$json = substr($raw_string, strpos($raw_string, '{'));
$object = json_decode($json);
What you got looks a bit like JSONP
(but isn't). Mostly a webservice offers parameters to either set the prefix (padding) or even omit it. If not try to replace it before paring as json. Also you need to replace the trailing ;
.. (not shown in question but should be present):
// replace the padding
$input = str_replace(' _result_ =', '', $input);
// replace the trailing ';'
$input = rtrim($input, ";")
// now parse as json
var_dump(json_decode($input));