我必须形成一个JSON字符串,其中一个值有新的行字符。这必须转义,然后使用AJAX调用发布。谁能建议一种用JavaScript转义字符串的方法?我没有使用jQuery。


当前回答

我使用内置的jQuery.serialize()从文本区域提取值以urlencode输入。专业的部分是,你不需要搜索替换每一个特殊的字符在你自己和我也保持换行符和转义html。为了序列化工作,似乎输入字段需要有一个name属性,但它也添加了相同的属性转义字符串,需要被替换掉。也许不是你想要的,但对我有用。

var myinputfield = jQuery("#myinputfield"); 
var text = myinputfield.serialize();
text = text.replace(myinputfield.attr('name') + '=','');

其他回答

使用encodeURIComponent()对字符串进行编码。

例如。var myEscapedJSONString = encodeURIComponent(JSON.stringify(myJSON));

你不需要解码它,因为web服务器会自动做同样的事情。

像你一样,我一直在寻找一些评论和帖子来替换我的JSON中包含html对象的特殊转义字符。

我的对象是删除JSON对象中的特殊字符,并渲染JSON对象内部的html。

以下是我所做的,希望使用起来非常简单。

首先我使用了JSON。stringify我的json对象和json。解析结果。

如:

JSON.parse(JSON.stringify(jsonObject));

它解决了我的问题,并使用纯Javascript。

这是一个旧帖子。但对于那些使用angular.fromJson和JSON.stringify的人来说,它仍然是有帮助的。 已弃用Escape()。 用这个代替,

var uri_enc = encodeURIComponent(uri); //before you post the contents
var uri_dec = decodeURIComponent(uri_enc); //before you display/use the contents.

ref http://www.w3schools.com/jsref/jsref_decodeuricomponent.asp

RegExp单行,使用这个函数:

function escapeJSON(string) {
    return string.replace(/[\n"\&\r\t\b\f]/g, '\\$&');
}

EDIT: Check if the api you’re interacting with is set to Content-Type: application/json, &/or if your client http library is both stringify-ing and parsing the http request body behind the scenes. My client library was generated by swagger, and was the reason I needed to apply these hacks, as the client library was stringifying my pre-stringified body (body: “jsonString”, instead of body: { ...normal payload }). All I had to do was change the api to Content-Type: text/plain, which removed the JSON stringify/parsing on that route, and then none of these hacks were needed. You can also change only the "consumes" or "produces" portion of the api, see here.

原文:如果你的谷歌一直登陆你这里,你的api抛出错误,除非你的JSON双引号转义("{\"foo\": true}"),所有你需要做的是stringify两次,例如JSON.stringify(JSON.stringify(bar)))