Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Dealing with JSONish things in PHP

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)

like image 280
Alan Storm Avatar asked Feb 05 '18 22:02

Alan Storm


People also ask

How to handle JSON in PHP?

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.

Can we use JSON parse in PHP?

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.

How to parse string to JSON in PHP?

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);


2 Answers

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.

like image 179
ob-ivan Avatar answered Oct 10 '22 18:10

ob-ivan


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.

like image 3
sorak Avatar answered Oct 10 '22 17:10

sorak