alihoushyaripour's avatar

How to remove whitespace from json string?

Hi,

I have a table with a column that has json type and when I want to insert data on it, json string has many whitespace, this is my code:

// parameters
$users = User::where(1);
$json = json_encode(UserResource::collection($users));

// insert
History::create([
    'type' => 'user',
    'data' => $json,
    // other parameters
]);

How to remove all whitespace from json?

0 likes
2 replies
lostdreamer_nl's avatar

Isn't the UserResource already returning json? How about this?:

$json = json_encode(UserResource::collection($users)->toArray());

If this also has 'many whitespace' could you post an example so we can see what whitespace you are talking about?

2 likes
aurawindsurfing's avatar

Hi,

There are some older methods that can be used with encoding json:

$final_json->toJson(JSON_PRETTY_PRINT | JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES));

Here are all the predefined constants you can use: http://php.net/manual/en/json.constants.php

This does the trick for me.

Hope it helps!

1 like

Please or to participate in this conversation.