简体   繁体   中英

Why doesn't json_encode($arr) not return a true string?

Instead of this "{\\"name\\":\\"Shares Magazine\\"}" I want this {"name":"Shares Magazine"} .

To achieve this, I am doing this json_encode(["name" => $user->reference_source], JSON_UNESCAPED_SLASHES);

To no avail, as this always ends up in the database "{\\"name\\":\\"Shares Magazine\\"}" .

I'm assuming you're using a json type column in your database

Schema::create('articles', function (Blueprint $table) {
    $table->id();
    $table->json('json_column');
});

And you're also casting in your model

class Article extends Model
{
    protected $casts = [
        'json_column' => 'json',
    ];
}

Then you don't need to cast before saving. Otherwise you're ending with a double cast. Laravel does that for you.

Article::create([
    'json_column' => ['name' => 'Shares Magazine'],
]);

And it be will saved as {"name": "Shares Magazine"} .

在编码你的 JSON 后试试这个(这比JSON_UNESCAPED_SLASHES效果更好):

$json = preg_replace('/\\\"/',"\"", $json);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM