处理PHP中的JSONish事物

时间:2022-10-28 22:32:25

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

我正在使用PHP来使用不属于我的服务。这个服务返回几乎但不完全不同于JSON(帽子提示,HGG)的东西。

i.e., in their simplest form, they look like this

即,最简单的形式,它们看起来像这样

{a: 8531329}

Running the above string through json_decode returns NULL

通过json_decode运行上面的字符串返回NULL

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

The problem is that a isn't quoted.

问题是a没有引用。

$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(本机或通过常见的包装包)是否为我提供了一种方法来将这个“valid-javascript-but-not-valid-json”字符串解析为PHP数组或stdClass?或者我自己会解析这个? (我上面的例子是一个简单的例子 - 实际字符串相当大)

2 个解决方案

#1


5  

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

JSON5可能是您所需要的:https://github.com/colinodell/json5

It deals with all things that object literals in JavaScript are allowed to have while JSON isn't.

它处理允许JavaScript中的对象文字而JSON不允许的所有内容。

#2


3  

If we define the input string as $i:

如果我们将输入字符串定义为$ i:

$i='{a: 8531329}';

We can pre-process it to make it valid JSON with preg_replace:

我们可以预处理它以使其与preg_replace一起使用它是有效的JSON:

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.

当然,我需要看到更多需要纠正的内容,以提供完整的解决方案。

#1


5  

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

JSON5可能是您所需要的:https://github.com/colinodell/json5

It deals with all things that object literals in JavaScript are allowed to have while JSON isn't.

它处理允许JavaScript中的对象文字而JSON不允许的所有内容。

#2


3  

If we define the input string as $i:

如果我们将输入字符串定义为$ i:

$i='{a: 8531329}';

We can pre-process it to make it valid JSON with preg_replace:

我们可以预处理它以使其与preg_replace一起使用它是有效的JSON:

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.

当然,我需要看到更多需要纠正的内容,以提供完整的解决方案。