Test HTTP Requests Tools Blog Learn Quizzes Smile API Log In / Sign Up
Test HTTP Requests Tools Blog Learn Quizzes Smile API Log In / Sign Up
« Return to the tutorials list
We have updated the website and our policies to make sure your privacy rights and security are respected.
Click here to learn more about the way our website handles your data.

Remove this message.

PHP - a few tips for working with JSON

Daniel Gheorghe Difficulty: 15 / 50 Tweet

JSON (JavaScript Object Notation) is a common, language independent, easy to read and parse representation of objects as strings.

In PHP, working with JSON is mostly trivial. However, there are a few gotchas and some less known options that can make your life easier. I'll go through and explain some of them below.

Error handling when decoding

When decoding JSON a few things can go wrong but the most common problem happens when the JSON syntax is invalid.

Here's an example of a JSON string with invalid syntax caused by the last comma.

        "key1": "value1",
        "key2": "value2",

If you were to try and decode the string above, the return value would be NULL, but the same value would return if you would try to decode the NULL string too. This can cause serious headaches. Have a look:

    $json_string = '{
        "key1": "value1",
        "key2": "value2",
    var_dump(json_decode($json_string)); // NULL
    $json_string = 'NULL';
    var_dump(json_decode($json_string)); // NULL

The way you would make sure you're not dealing with a JSON error is by using the json_last_error function.

Here's an example, using the above JSON string.

    $decoded_json = json_decode($json_string);
    if( json_last_error()===JSON_ERROR_NONE ) {
        // the JSON is valid.


If you're lucky enough to work on a project that is compatible with a newer version of PHP, as of PHP 7.3 you can use the JSON_THROW_ON_ERROR constant to throw an exception when a json_encode or json_decode error occurs.

In this, cade the code above can be rewritten like this:

    try { 
        var_dump(json_decode($json_string, false, 512, JSON_THROW_ON_ERROR));
    } catch (JsonException $e) {
        echo $e->getMessage() . PHP_EOL;
        //Syntax error

Pretty print

I've seen log files with JSON encoded debug data in them that was not formatted in any way. This made debugging almost impossible unless you copied that data pasted it into a formatter and then inspected the contents.

Luckily, PHP has a method of showing in a much more readable fashion, using whitespace to format the JSON string.

Here's how a simple array looks like when printed with and without JSON_PRETTY_PRINT. Imagine how the first output looks like when dataset becomes huge.

    $x = ["name"=> "John", "age"=> "30"];
    echo json_encode($x) . PHP_EOL;
    echo json_encode($x, JSON_PRETTY_PRINT) . PHP_EOL;
        "name": "John",
        "age": "30"