Categories


Archives


Recent Posts


Categories


Using “Not Quite JSON” with PHP

astorm

Frustrated by Magento? Then you’ll love Commerce Bug, the must have debugging extension for anyone using Magento. Whether you’re just starting out or you’re a seasoned pro, Commerce Bug will save you and your team hours everyday. Grab a copy and start working with Magento instead of against it.

Updated for Magento 2! No Frills Magento Layout is the only Magento front end book you'll ever need. Get your copy today!

One of the odd side effects of JSON’s wide spread success is how often you’ll run across data that’s not quite json

A hello world example looks something like this

{a: "Hello World"}

If you look at that string, you might think Hey, it’s a JSON string! However, it’s not strict JSON — the a needs to be a quoted string. Consider the output of the following.

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

$bar = json_decode('{"a": 8531329}');
var_dump($bar); //the object

“Not Quite JSON” exists because JSON’s elevator pitch is

We encode everything using javacsript objects

This means there’s a ton of JSON code out there that parses and produce things that are valid javascript, but not valid JSON. Unfortuntly, PHP’s json_encode/json_decode can’t handle things that aren’t valid JSON.

The colinodell/json5 Packagist package seems to solve this for PHP. I’m not familiar with the JSON5 format it implements, but so far it has parsed all the almost, but not quite, JSON strings I’ve thrown at it.

Copyright © Alana Storm 1975 – 2023 All Rights Reserved

Originally Posted: 13th February 2018

email hidden; JavaScript is required