Array to JSON with toJson() Method

toJson() is one of the most helpful and commonly used method in Laravel. In simple concept, toJson() returns the JSON encoded data version of laravel array or collection. This method takes one optional parameter i.e. $options.

This method is very much similar to json_encode() in PHP.

Structure

toJson() is located in Illuminate/Support/Collection. It’s structure is like:

/**
 * Get the collection of items as JSON.
 *
 * @param  int  $options
 * @return string
 */
public function toJson($options = 0)
{
    return json_encode($this->jsonSerialize(), $options);
}

Let’s practice Array to JSON converison

At first, lets talk about how we can use toJson() method.

// Create a new collection
$collection = new Collection([
    ['name' =>  'PS5', 'price'    =>  899],
    ['name' =>  'PS2', 'price'    =>  199],
]);

// Convert the collection to JSON format
$jsonValue = $collection->toJson();

As shown in the above example, first of all an array is declared which is later converted in JSON. The result of above example look like this:

[{"name":"PS5","price":899},{"name":"PS2","price":199}]

For printing the formatted value, we can pass JSON_PRETTY_PRINT as parameter:

$jsonValue = $collection->toJson(JSON_PRETTY_PRINT);

After that, if we print the variable we will get result something like this:

[
    {
        "name": "PS5",
        "price": 899
    },
    {
        "name": "PS2",
        "price": 199
    }
]

Nested Data Structure and toJson()

Specification of the depth of array to which data will be encoded is not provided by toJson() method. It is set to 512 by default. But if the user wants to go to deeper than 512 then user can take this approach:


use Illuminate\Support\Collection;

// Create a new collection instance.
$collection = new Collection([]);

// Replace 512 with the desired depth.
$jsonValue = json_encode(
    $collection->jsonSerialize(),
    0,
    512
);

These are all the basics of toJson() method. Hope you enjoyed this tutorial;)

For more tutorials click here

Total
0
Shares
Leave a Reply

Your email address will not be published.

Related Posts
Total
0
Share