0
0

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 1 year has passed since last update.

JSON.parseで改行がある文字列の注意点

Last updated at Posted at 2023-11-13

DBから取得したJSONの文字列がこんなようにします

{"text":"text検証\n test"}

JSONの文字列なので、textの値を取得したい場合、JSON.parse()が使われます。しかし、以下のエラーが発生します。

undefined:1
{"text":"text検証
               ^
SyntaxError: Unexpected token 
 in JSON at position 15
    at JSON.parse (<anonymous>)

原因は、JSON.parse()を使いたいが、制御文字が含まれているため、\n\\nに変更する必要があります。

const str = '{"text":"text検証\\n test"}'
console.log(JSON.parse(str))

結果は

{ text: 'text検証\n test' }

問題ありません。

0
0
1

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
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?