Be part of JetBrains PHPverse 2026 on June 9 – a free online event bringing PHP devs worldwide together.

samirapadidar's avatar

How to convert array to json

I was trying to convert an array to json and this is my code

private function prepareLogData(Request $request)
    {
      return json_encode([
           'ip' => $request->ip(),
           'url' => $request->url(),
           'agent' => $request->userAgent(),
           'date' => Carbon::now()->toDateTimeString(),
           'params' => $request->query(),
       ]);

    }

But then when I tested the output of this code, I realized that it returns a string. this is my code

 dd(is_string(json_encode([
            'ip' => $request->ip(),
            'url' => $request->url(),
            'agent' => $request->userAgent(),
            'date' => Carbon::now()->toDateTimeString(),
            'params' => $request->query(),
        ])));

return the true output how can convert this array to json???

0 likes
8 replies
SilenceBringer's avatar

@samirapadidar I have surprise for you: json is a string!

for example

'{foo:"bar"}'

it's string, but contains correct json data which can be parsed and processed

samirapadidar's avatar

@SilenceBringer thanks for your reply Ok you wone! this is my output

"message":"{\"ip\":\"127.0.0.1\",\"url\":\"http:\/\/127.0.0.1:8001\/api\/index\",\"agent\":\"Mozilla\/5.0 (X11; Linux x86_64) AppleWebKit\/537.36 (KHTML, like Gecko)..."

But I do not want "" Be a messenger in response and convert to the following output

{"ip":"127.0.0.1","url":"http:127.0.0.1:8001api/index","agent":"Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko)...

how can I do it? pleas help me!!

samirapadidar's avatar

@SilenceBringer

<?php

namespace App\Http\Middleware;

use Carbon\Carbon;
use Closure;
use Illuminate\Http\RedirectResponse;
use Illuminate\Http\Request;
use Illuminate\Http\Response;
use Illuminate\Support\Facades\Log;

class SystemActivityLogger
{
    /**
     * Handle an incoming request.
     *
     * @param \Illuminate\Http\Request $request
     * @param \Closure(\Illuminate\Http\Request): (\Illuminate\Http\Response|\Illuminate\Http\RedirectResponse)  $next
     * @return Response|RedirectResponse
     */
    public function handle(Request $request, Closure $next)
    {
        Log::channel('rabbitmq_elk')->info($this->prepareLogData($request));
        return $next($request);
    }

    /**
     * Prepare log data and log it
     * @param Request $request
     * @return string
     */
    private function prepareLogData(Request $request)
    {
      return json_encode([
           'ip' => $request->ip(),
           'url' => $request->url(),
           'agent' => $request->userAgent(),
           'date' => Carbon::now()->toDateTimeString(),
           'params' => $request->query(),
       ]);

    }
}

This is my all code

MohamedTammam's avatar

That's how JSON works, JSON is a string format.

To get it as an object in front-end you need to convert it back to an object using Javascript

JSON.parse(yourString) // Will return an object

If you're using fetch

fetch('url').then(res => res.json()).then(data => {
	// "data" is an object.
})

And in your Laravel you don't have to use json_encode to return a JSON. You can use a better method under response.

return response()->json([
           'ip' => $request->ip(),
           'url' => $request->url(),
           'agent' => $request->userAgent(),
           'date' => Carbon::now()->toDateTimeString(),
           'params' => $request->query(),
       ]);

samirapadidar's avatar

@MohamedTammam i tested it but return following output

"message":"HTTP/1.0 200 OK\r\nCache-Control: no-cache, private\r\nContent-Type: application/json\r\nDate: Sun, 23 Oct 2022 11:13:09 GMT\r\n\r\n{\"ip\":\"127.0.0.1\",\"url\":\"http:\/\/127.0.0.1:8001\/api\/index\",\"agent\":\"Mozilla\/5.0 (X11..."
MohamedTammam's avatar

@samirapadidar Oh sorry, I didn't know that you're using it for logger. I thought you're doing it for a response for front-end. Then yeah, use json_encode :)

return json_encode([
           'ip' => $request->ip(),
           'url' => $request->url(),
           'agent' => $request->userAgent(),
           'date' => Carbon::now()->toDateTimeString(),
           'params' => $request->query(),
       ]);
samirapadidar's avatar

@MohamedTammam I tried the same but it returns me a string when I want it to be a json object this is my kibana discover

@timestampOct 23, 2022 @ 14:55:[email protected]_stream.typelogsevent.original{"@timestamp":"2022-10-23T11:25:45.815859+00:00","@version":1,"host":"elk.kifarunix-demo.com","message":"{\"ip\":\"127.0.0.1\",\"url\":\"http:\/\/127.0.0.1:8003\/api\/index\",\"agent\":\"Mozilla\/5.0 (X11; Linux x86_64) AppleWebKit\/537.36 (KHTML, like Gecko) Chrome\/104.0.0.0 Safari\/537.36\",\"date\":\"2022-10-23 11:25:45\",\"params\":[]}","type":"Laravel","channel":"logstash.main","level":"INFO","monolog_level":200} hostelk.kifarunix-demo.comlevelINFOmessage{"ip":"127.0.0.1","url":"http:\/\/127.0.0.1:8003\/api\/index","agent":"Mozilla\/5.0 (X11; Linux x86_64) AppleWebKit\/537.36 (KHTML, like Gecko) Chrome\/104.0.0.0 Safari\/537.36","date":"2022-10-23 11:25:45","params":[]}monolog_level200typeLaravel_idvP6XBIQBSVWbrkPbdvk__indexmy-index-000001_score -

I want the message to be an object so that I can search on it in Kibana

A search like below ‍‍message.ip

Please or to participate in this conversation.