0
2

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 3 years have passed since last update.

Laravelで作成したAPIをJSON形式で返すときに文字化けする

Posted at

APIを作成がなんのこっちゃな初学者がこの記事を参考にAPIを作成したら、JSON形式で返すときに文字化けして、それを解決したので書きました。

文字化け

こんな感じの文字化けです。
スクリーンショット 2021-03-27 13.26.50.png
実際には{"result":true,"title":"テスト","naiyo":"テストです。"}と出力されてほしい。

解決

response()->json()のオプションにJSON_UNESCAPED_UNICODEを追加するだけです。
あらかじめ、JSON_UNESCAPED_SLASHESというオプションを入れているため、
JSON_UNESCAPED_SLASHES | JSON_UNESCAPED_UNICODEと繋げてあげます。

JSON_UNESCAPED_SLASHES とは

/ のエスケープをしないようにするオプションです。
これを設定しておかないと、/ の前に \ が入ってしまいます。(今回の場合だと無くても良い)
例) https:\/\/hogehoge.comhttps://hogehoge.com

参考:PHP の json_encode で変換後の文字列を僕が読みやすいようにする

0
2
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
2

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?