NikiCs´ answer is already spot on. Your input seems to be manually generated, so it's entirely possible that within '
single quoted strings, you'll receive unquoted "
doubles. A regex assertion is therefore advisable instead of a plain search and replace.
But there are also a few userland JSON parsers which support a bit more Javascript expression syntax. It's probably best to speak of JSOL, JavaScript Object Literals, at this point.
Services_JSON can decode:
- unquoted object keys
- and strings enclosed in single quotes.
No additional options are required, just = (new Services_JSON)->decode($jsol);
This was actually meant as fallback for early PHP versions without JSON extension. It reimplements PHPs json_decode()
. But there's also the upgrade.php.prefixed
version, which you'd use here.
It introduces an additional flag JSON_PARSE_JAVASCRIPT
.
up_json_decode($jsol, false, 512, JSON_PARSE_JAVASCRIPT);
And I totally forgot about mentionind this in the docs, but it also supports single-quoted strings.
For instance:
{ num: 123, "key": "value", 'single': 'with \' and unquoted " dbls' }
Will decode into:
stdClass Object
(
[num] => 123
[key] => value
[single] => with ' and unquoted " double quotes
)
Other options
JasonDecoder by @ArtisticPhoenix does support unquoted keys and literals, though no '
-quoted strings. It's easy to understand or extend however.
YAML (1.2) is a superset of JSON, and most parsers support both unquoted keys or single-quoted strings. See also PHP YAML Parsers
Obviously any JSOL tokenizer/parser in userland is measurably slower than just preprocessing malformed JSON. If you expect no further gotchas from your webservice, go for the regex/quote conversion instead.