Monday, October 8, 2018

PHP json_decode Gotcha

Before you go crazy figuring out what went wrong, be aware of these when using json_decode.
// single quotes are not valid 
$bad_json = "{ 'bar': 'baz' }";
json_decode($bad_json); // null

// the name must be enclosed in double quotes
$bad_json = '{ bar: "baz" }';
json_decode($bad_json); // null

// trailing commas are not allowed
$bad_json = '{ bar: "baz", }';
json_decode($bad_json); // null

This is the one that would work.
// use double quotes
$good_json = '{ "bar": "baz" }';
json_decode($good_json);

No comments:

Post a Comment

Note: Only a member of this blog may post a comment.