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

查看:35
本文介绍了如何处理 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

"}';
var dataObj = eval('('+data+')');

这给了我一个错误:

unterminated string literal

使用 JSON.parse(data),我看到类似的错误消息:Chrome 中的Unexpected token ↵"和未终止的字符串文字" 在 Firefox 和 IE 中.

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

当我在 sometext 之后取出 时,两种情况下的错误都会消失.我似乎无法弄清楚为什么 使 evalJSON.parse 失败.

When I take out the after sometext the error goes away in both cases. I can't seem to figure out why the 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天全站免登陆