How to Convert JSON to Array in Laravel?

By Hardik Savani April 16, 2024 Category : Laravel

Hello Friends,

In this guide, we are going to learn how to convert json to array in laravel. I explained simply about how to convert json into array in laravel. This post will give you a simple example of how to convert json object to array in laravel. If you have a question about laravel convert json to array then I will give a simple example with a solution.

You can use this example with laravel 6, laravel 7, laravel 8, laravel 9, laravel 10 and laravel 11 versions.

There are several different ways to convert JSON data into an array in Laravel application. In this example, I will give you two ways to convert JSON data into an array. in the first example, we will use json_decode() and in the second example, we will use json() method of HTTP response. so, let's see both examples one by one.

Example 1: Using json_decode()

app/Http/Controllers/DemoController.php

<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;

class DemoController extends Controller

{

/**

* Write code on Method

*

* @return response()

*/

public function index(Request $request)

{

$jsonData = '[

{ "id": 1, "name": "Hardik", "email": "hardik@gmail.com"},

{ "id": 2, "name": "Vimal", "email": "vimal@gmail.com"},

{ "id": 3, "name": "Harshad", "email": "harshad@gmail.com"}

]';

$data = json_decode($jsonData, true);

dd($data);

}

}

Output:

Array

(

[0] => Array

(

[id] => 1

[name] => Hardik

[email] => hardik@gmail.com

)

[1] => Array

(

[id] => 2

[name] => Vimal

[email] => vimal@gmail.com

)

[2] => Array

(

[id] => 3

[name] => Harshad

[email] => harshad@gmail.com

)

)

Example 2: Using json() Method

app/Http/Controllers/DemoController.php

<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;

use Illuminate\Support\Facades\Http;

class DemoController extends Controller

{

/**

* Write code on Method

*

* @return response()

*/

public function index(Request $request)

{

$response = Http::get('https://jsonplaceholder.typicode.com/posts/1');

$data = $response->json();

dd($data);

}

}

Output:

Array

(

[userId] => 1

[id] => 1

[title] => sunt aut facere repellat provident occaecati excepturi optio reprehenderit

[body] => quia et suscipit

suscipit recusandae consequuntur expedita et cum

reprehenderit molestiae ut ut quas totam

nostrum rerum est autem sunt rem eveniet architecto

)

I hope it can help you...

Tags :
Shares