Working with JSONish in PHP

I use PHP to use a service that is not mine. This service returns those things that are almost, but not quite, completely different from JSON (tip tip, HGG).

ie, in their simplest form, they look like this:

{a: 8531329} 

Running the specified string through json_decode returns NULL

 $foo = json_decode('{a: 8531329}'); 

The problem is that a not quoted.

 $foo = json_decode('{"a": 8531329}'); 

Does PHP (both initially and through regular packagist packages) offer a method for parsing this string "valid-javascript-but-not-valid-json" into a PHP array or stdClass? Or did I figure it out myself? (my example above is a simple case - the actual strings are quite large)

+5
source share
2 answers

JSON5 might be what you need: https://github.com/colinodell/json5

It deals with all the things that object literals in JavaScript are allowed to have, but JSON is not.

+5
source

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 fixed in order to provide a complete solution, of course.

+3
source

Source: https://habr.com/ru/post/1275181/


All Articles