
How To Convert Json To Array In Laravel
Hello Devs,
Today I will show you how we can convert JSON to array in laravel. There are several methods used to convert JSON to ARRAY.
This post will give you a simple example that how we can convert a JSON object to an array.
I will try to explain it in a simple way. In this post, I will use 2 ways to convert the JSON to an array.
In first example I will use simple php method json_decode(). In the second method, I will json() method to convert JSON to an array over an HTTP response.
You can try these methods on any version of Laravel. I have tested it on Laravel 9.
First of all, I created DemoController and 2 routes to show you examples.
Example 1 : json_decode() method
app/Http/Controllers/DemoController.php
json_decode_mehod function in controller.
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Http;
class DemoController extends Controller
{
public function json_decode_mehod() {
$json_data = '{
"userId": 1,
"id": 1,
"title": "sunt aut facere repellat provident occaecati excepturi optio reprehenderit",
"body": "quia et suscipit\nsuscipit recusandae consequuntur expedita et cum\nreprehenderit molestiae ut ut quas totam\nnostrum rerum est autem sunt rem eveniet architecto"
}';
$data = json_decode($json_data, true);
print_r($data);
}
}
In this example, I am using the json_decode() method to convert the JSON string to an array. You can also use this method in the code PHP and other PHP frameworks.
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
)
Example 2 : json() methhod
app/Http/Controllers/DemoController.php
json_mehod function in controller.
namespace App\Http\Controllers; use Illuminate\Http\Request; use Illuminate\Support\Facades\Http; class DemoController extends Controller { public function json_method() { $response = Http::get('https://jsonplaceholder.typicode.com/posts/1'); print_r($response->json()); } }
In this example, I am using an HTTP request to fetch the JSON object from the URL.
Then I use json() method to convert the response to the array.
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
)
If you have any confusion or suggestion about this post. you can comment on the post.
Thanks, I hope it can help you.