You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

PHP解析非标准JSON:合法JS对象转PHP数组/对象的方案问询

Parsing JS-like (Unquoted Key) Strings to PHP Arrays/Objects

Hey there! I totally feel your pain with those almost-JSON responses that skip quotes around keys—nothing’s more frustrating than running json_decode() and getting a useless NULL back. The good news is you don’t have to build a parser from scratch; there are both native PHP workarounds and reliable Packagist packages to handle this mess. Let’s break down your options:

Native PHP Workarounds

No external dependencies needed, but keep their limitations in mind:

1. Regex to Patch the JSON (Quick but Not Bulletproof)

You can use preg_replace() to wrap unquoted keys in double quotes, then feed the fixed string to json_decode(). A basic regex for this looks like:

$rawInput = '{name: "HGG", id: 123, tag: "almost-json"}';
// Regex matches unquoted word-like keys before a colon
$fixedJson = preg_replace('/(?<!["\'\w])\w+(?=\s*:)/', '"$0"', $rawInput);
$data = json_decode($fixedJson, true); // Pass true for array, omit for stdClass

Heads up: This works for simple keys (letters, numbers, underscores) but will fail if keys have spaces, hyphens, or special characters. It might also accidentally quote values if they match the pattern, so test it thoroughly with your actual response data.

2. eval() (Only for 100% Trusted Data!)

If you’re absolutely certain the third-party service won’t send malicious code (like if it’s an internal tool you control), you can use eval() to parse the string directly as PHP syntax:

$rawInput = '{name: "HGG", id: 123}';
// Wrap in parentheses to avoid syntax quirks, then evaluate
$data = eval("return $rawInput;");

Big Red Warning: eval() executes arbitrary code, so never use this for untrusted input—it’s a massive security risk. This is a last-resort for controlled, trusted sources only.

3. V8JS Extension (If Your Host Supports It)

If your server has the V8JS extension installed, you can use the actual Chrome V8 engine to parse the JS object and convert it to PHP:

$v8 = new V8Js();
$rawInput = '{name: "HGG", id: 123}';
// Wrap in parentheses to treat the object as an executable expression
$jsObject = $v8->executeString('(' . $rawInput . ')');
$phpArray = (array) $jsObject;

This is way more reliable than regex because it uses a real JS parser, but it requires installing an extension that isn’t available on all shared hosts.

Trusted Packagist Packages

For a robust, secure solution that handles edge cases, these packages are your best bet:

1. json5/json5 (Purpose-Built for Non-Standard JSON)

JSON5 is a superset of JSON that allows unquoted keys, trailing commas, and other JS-friendly syntax—exactly what you’re dealing with. This package parses JSON5 directly into PHP arrays or objects:

use JSON5\JSON5;

$rawInput = '{name: "HGG", id: 123, nested: {key: "value"}}';
$data = JSON5::decode($rawInput, true); // true returns an array, false returns stdClass

It’s actively maintained, handles all the edge cases regex misses, and is the most straightforward solution for this exact problem.

2. symfony/yaml (Surprisingly Versatile)

Wait, YAML? Hear me out—YAML is a superset of JSON, and most JS-like object syntaxes are valid YAML. Symfony’s YAML component can parse your string into PHP data structures:

use Symfony\Component\Yaml\Yaml;

$rawInput = '{name: "HGG", id: 123, "key-with-spaces": "value"}';
// Use PARSE_OBJECT_FOR_MAP if you want stdClass instead of an array
$data = Yaml::parse($rawInput, Yaml::PARSE_OBJECT_FOR_MAP);

This works great if you already use Symfony components in your project, and it handles keys with spaces or special characters (as long as they’re quoted in the input).

3. mtdowling/jmespath.php (Parse + Query in One)

While JMESPath is mainly for querying JSON-like data, its parser can handle unquoted keys. You can parse the string into a PHP array and then use JMESPath to extract data if needed:

use JmesPath\Env;

$rawInput = '{name: "HGG", id: 123}';
$parser = Env::getParser();
// Pass an empty array to get the full parsed dataset
$data = $parser->parse($rawInput)->search([]);

It’s a solid choice if you need to query or manipulate the parsed data after parsing.

When Should You Write Your Own Parser?

Only if all the above options fail—like if the response has extremely weird edge cases that none of the regexes or packages can handle. But that’s rare; the methods above should cover 99% of scenarios you’ll encounter.

内容的提问来源于stack exchange,提问作者Alana Storm

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.19 04:02:44