带换行符的JSON.parse [英] JSON.parse with newline

查看:224
本文介绍了带换行符的JSON.parse的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

为什么你不能用javascript中的 \ n 字符解析json

Why can't you parse a json with a \n character in javascript

JSON.parse('{x:\ n}')

但是当你做<$ c时$ c> JSON.parse(JSON.stringify({x:\ n})),它是有效的。

However when you do JSON.parse(JSON.stringify({"x" : "\n"})), it is valid.

http://www.jslint.com/ {x: \ n} 是一个有效的JSON。我想知道规范对此有何看法?

http://www.jslint.com/ says that {"x": "\n"} is a valid JSON. I wonder what does spec says about this?

更新:
对于那些标有此副本的人,这不是同一个问题作为如何处理JSON中的换行符。这个问题更多的是为什么不能在JSON中允许未转义的换行符。

Update: For those who marked this duplicate, this is not the same question as "How to handle newlines in JSON". This question is more about why can't an unescaped newline character allowed in JSON.

推荐答案

JSON。解析('{x:\ n}})失败,因为'{x:\ n}}'由于未转义的斜杠符号,因此不是有效的JSON字符串。

JSON.parse('{"x": "\n"}') fails because '{"x": "\n"}' is not a valid JSON string due to the unescaped slash symbol.

JSON.parse()需要有效JSON字符串可以工作。

JSON.parse() requires a valid JSON string to work.

'{x:\\ n}'是一个现在有效的JSON字符串,因为斜杠现在被转义,所以 JSON.parse('{x:\\ n}')将起作用。

'{"x": "\\n"}' is a valid JSON string as the slash is now escaped, so JSON.parse('{"x": "\\n"}') will work.

JSON.parse(JSON.stringify({x:\ n}))因为JSON而起作用。 stringify在内部转义斜杠字符。

JSON.parse(JSON.stringify({"x" : "\n"})) works because JSON.stringify internally escapes the slash character.

JSON.stringify({x:\ n}} {x:\ n}} 但是如果你尝试使用 JSON.parse('{来解析它x:\ n})'它将失败,因为它没有被转义。当JSON.stringify返回一个转义字符时, JSON.parse(JSON.stringify())将起作用。

The result of JSON.stringify({"x" : "\n"}) is {"x":"\n"} but if you try to parse this using JSON.parse('{"x":"\n"})' it will FAIL, as it is not escaped. As JSON.stringify returns an escaped character, JSON.parse(JSON.stringify()) will work.

这篇关于带换行符的JSON.parse的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆