如何处理JSON中的换行符? [英] How do I handle newlines in JSON?

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

问题描述

我已经生成了一些JSON,我试图将它拉入JavaScript中的对象。我一直在收到错误。这就是我所拥有的:

I've generated some JSON and I'm trying to pull it into an object in JavaScript. I keep getting errors. Here's what I have:

var data = '{"count" : 1, "stack" : "sometext\n\n"}';
var dataObj = eval('('+data+')');

这给了我一个错误:

unterminated string literal

使用 JSON。解析(数据),我在Chrome中看到类似的错误消息:意外的令牌↵,以及未终止的字符串文字在Firefox和IE浏览器中。

With JSON.parse(data), I see similar error messages: "Unexpected token ↵" in Chrome, and "unterminated string literal" in Firefox and IE.

当我取出 \ n 之后 sometext 这两种情况都会消失。我似乎无法弄清楚为什么 \ n 使 eval JSON。解析失败。

When I take out the \n after sometext the error goes away in both cases. I can't seem to figure out why the \n makes eval and JSON.parse fail.

推荐答案

我想这就是你想要的:

var data = '{"count" : 1, "stack" : "sometext\\n\\n"}';

(您需要转义字符串中的\(将其变为双 - \),否则它将成为JSON源中的换行符,而不是JSON数据。)

(You need to escape the "\" in your string (turning it into a double-"\"), otherwise it will become a newline in the JSON source, not the JSON data.)

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

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