I'm using PHP to consume a service that is not mine. This service returns things that are almost, but not quite, entirely unlike JSON (hat tip, HGG).
i.e., in their simplest form, they look like this
{a: 8531329}
Running the above string through json_decode
returns NULL
$foo = json_decode('{a: 8531329}');
The problem is that a
isn't quoted.
$foo = json_decode('{"a": 8531329}');
Does PHP (either natively or via common packagist packages) offer me a way to parse this "valid-javascript-but-not-valid-json" string into a PHP array or stdClass? Or will I be parsing this myself? (my example above is a simple case -- actual strings are rather large)
PHP File explained:Convert the request into an object, using the PHP function json_decode(). Access the database, and fill an array with the requested data. Add the array to an object, and return the object as JSON using the json_encode() function.
Parsing JSON with PHPPHP has built-in functions to encode and decode JSON data. These functions are json_encode() and json_decode() , respectively. Both functions only works with UTF-8 encoded string data.
To convert it back to an object use this method: $jObj = json_decode($jsonString); And to convert it to a associative array, set the second parameter to true : $jArr = json_decode($jsonString, true);
JSON5 may be what you need: https://github.com/colinodell/json5
It deals with all things that object literals in JavaScript are allowed to have while JSON isn't.
If we define the input string as $i
:
$i='{a: 8531329}';
We can pre-process it to make it valid JSON with preg_replace
:
json_decode(preg_replace('/\{([^:]*):/', '{"\1":', $i))
I would need to see a larger set of what needs to be corrected to provide a complete solution, of course.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With