Work With JSON in PHP – CloudSavvy IT

Posted on

PHP Logo

JSON is likely one of the mostly used information serialization codecs. It’s grown from its origins inside JavaScript (JSON means JavaScript Object Notation) to grow to be the format of selection for a lot of internet APIs and configuration techniques.

PHP ships with built-in JSON assist. Traditionally, the options have been offered as a separate extension. The 2020 launch of PHP 8.0 transformed JSON into a permanently active extension which can’t be eliminated.

Studying JSON Information

To parse JSON information, use the json_decode() operate. Its full signature is as follows:

json_decode(string $json, bool|null $associative=null, int $depth=512, int $flags=0) : combined;

The best invocation is to move a JSON string with no different arguments. We’ll work with {"foo": "bar"} which decodes to an occasion of PHP’s generic stdClass. Our new object may have a property foo with the worth of bar.

In the event you’d moderately obtain an associative array, move true to the $associative parameter of json_decode(). The above instance would then decode to ["foo" => "bar"].

The $depth parameter helps you to management the utmost nesting degree to parse right down to. You’ll get null if the JSON nests deeper than the set degree – no try shall be made to parse the information.

The $flags parameter accepts a bitmask of non-obligatory flags that alter the parsing behaviour. These are described in detail inside the PHP handbook and assist you to outline how particular information varieties ought to be dealt with.

Dealing with Parsing Errors

By default, json_decode() will return null when it’s handed an invalid JSON string. This presents a difficulty as a result of an remoted null is a legitimate JSON string. You’ve no approach of realizing whether or not the null return worth is because of the JSON containing null, or as a result of the JSON was malformed and couldn’t be parsed.

PHP 7.3 lastly addressed this longstanding drawback by including the JSON_THROW_ON_ERROR flag. Cross this fixed to the $flags parameter of json_decode() to make PHP throw an exception when invalid JSON is encountered:

json_decode("['malformed json", true, 512, JSON_THROW_ON_ERROR);

Enabling this behaviour is generally desirable but it does make for a rather unwieldy invocation. You can use PHP 8’s named arguments to simplify things a bit, as you won’t need to pass explicit values for the optional parameters:

json_decode(json: "['malformed json", flags: JSON_THROW_ON_ERROR);

The two examples shown above are equivalent to each other. The only difference is the latter syntax requires PHP 8.

Serializing data to JSON

You can serialize PHP values into JSON strings using the json_encode() function. Its signature is as follows:

json_encode(mixed $value, int $flags=0, int $depth=512) : string|false;

PHP accepts any value as $value, except for resources. Data types are automatically handled to ensure they have an appropriate mapping in the generated JSON. PHP objects and associative arrays will become JSON objects containing all the enumerable property/key-value pairs of the input value. PHP scalar types map directly into JSON with no transformation.

Like its decoding counterpart, json_encode() accepts $flags and $depth parameters. Take care around the order though – in a quirk of the PHP standard library, the position of these two optional parameters is switched compared to json_decode().

Many more flags are supported when encoding data. Here’s some to be aware of:

  • JSON_FORCE_OBJECT – Convert PHP numerical arrays to JSON objects instead of arrays. This handles the case where a variable contains an associative array which might be empty. When the array is empty ([]), a JSON array could be created; when it’s not empty (["foo" => "bar"]), an object could be emitted as a substitute. Enabling this flag ensures an object is at all times used within the encoded JSON.
  • JSON_PRETTY_PRINT – PHP’s JSON output is generally minified which is good when sending it over the community as a part of an HTTP request. Setting this flag will add new line characters and computerized indentation to the JSON string, making it extra appropriate for configuration information and different eventualities the place people will learn the output.
  • JSON_PRESERVE_ZERO_FRACTION – Forces PHP to encode floats comparable to 0.0 precisely, as a substitute of shaving off the fraction to put in writing 0 into the JSON (which might be incorrectly parsed as an integer).
  • JSON_NUMERIC_CHECK – Mechanically converts numeric strings to numbers within the JSON output, as a substitute of preserving them as strings. With this enabled, a PHP worth "234.5" shall be emitted as 234.5 within the JSON.
  • JSON_PARTIAL_OUTPUT_ON_ERROR – Attempt to proceed writing even after an encoding error is encountered. PHP will attempt to substitute invalid values with a purpose to produce some output, even when it’s not full.

You may get hold of the total list of flags inside the PHP documentation. The rest are largely particular choices to customize the encoding utilized in explicit eventualities.

Bringing JSON to Your Software’s Area Layer

Complicated internet backends are probably to make use of PHP’s JSON options inside the context of emitting HTTP responses. That in all probability means you’ll be encoding cases of domain-layer courses, comparable to BlogPost.

Calling json_encode() with an occasion of a category leads to a JSON string containing a single object. PHP will enumerate the public properties of the category and add them as key/worth pairs into the JSON-encoded object.

class BlogPost {
    protected int $Id = 1;
    public string $Title = "Instance";
// produces '{"Title": "Instance"}'
$json = json_encode(new BlogPost());

PHP can’t routinely entry protected or non-public properties. This default implementation is due to this fact inadequate for all however the easiest of courses. As a substitute, your courses can implement the JsonSerializable interface. This lets you outline how cases shall be remodeled to JSON.

JsonSerializable defines a single methodology, jsonSerialize(), which PHP will name every time an occasion must be serialised to JSON:

class BlogPost implements JsonSerializable {
    protected int $Id = 1;
    public string $Title = "Instance";
    public operate jsonSerialize() {
        return [
            "Id" => $this -> Id,
            "Title" => $this -> Title
// produces '{"Id": 1, "Title": "Instance"}'
$json = json_encode(new BlogPost());

Implementing JsonSerializable lets you take management of the serialization course of. Your cases can select what to show, which could embrace protected properties, dynamically computed values and information returned from methodology calls.

You don’t even have to return an array. The jsonSerializable methodology signature specifies a combined return kind, so you may present any worth which PHP can serialize to JSON. You can return one other object to have PHP serialize it recursively.

Source link

Gravatar Image
I love to share everything with you

Leave a Reply

Your email address will not be published. Required fields are marked *