javascript 如何在 JSON.stringfy 之后删除 \n?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/45995130/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to remove \n after JSON.stringfy?
提问by Morton
I parse the data from website and try to change to a json object.
我解析来自网站的数据并尝试更改为 json 对象。
Here is my function:
这是我的功能:
function outPutJSON() {
for (var i = 0; i < movieTitle.length; i++) {
var handleN = movieContent[i];
console.log('===\n');
console.log(handleN);
data.movie.push({
mpvieTitle: movieTitle[i],
movieEnTitle: movieEnTitle[i],
theDate: theDate[i],
theLength: theLength[i],
movieVersion: movieVersion[i],
youtubeId: twoId[i],
content: movieContent[i]
});
};
return JSON.stringify(data);
}
console.log will print movieContent[0] like:
console.log 将打印 movieContent[0] 像:
but i return JSON.stringfy(data);
it will become:

但我返回 JSON.stringfy(data); 它会变成:

There are so many /n i want to remove it.
有这么多/ni想删除它。
I try to change return JSON.stringfy(data);to this:
我尝试将返回更改JSON.stringfy(data);为:
var allMovieData = JSON.stringify(data);
allMovieData = allMovieData.replace(/\n/g, '');
return allMovieData;
It's not working the result is the same.
它不起作用,结果是一样的。
How to remove /n when i use JSON.stringfy()?
使用时如何删除/n JSON.stringfy()?
Any help would be appreciated . Thanks in advance.
任何帮助,将不胜感激 。提前致谢。
采纳答案by Cerbrus
In your data screenshots, you literally see"\n".
在您的数据屏幕截图中,您可以从字面上看到"\n".
This probably means that the actual string doesn't contain a newline character (\n), but a escaped newline character (\\n).
这可能意味着实际的字符串不包含换行符 ( \n),而是包含转义的换行符 ( \\n)。
A newline character would have been rendered as a linebreak. You wouldn't see the \n.
换行符会被渲染为换行符。你不会看到\n.
To remove those, use .replace(/\\n/g, '')instead of .replace(/\n/g, '')
要删除这些,请使用.replace(/\\n/g, '')而不是.replace(/\n/g, '')
回答by Jimmy Obonyo Abor
just :=>
JSON.stringify(JSON.parse(<json object>))
只是:=>
JSON.stringify(JSON.parse(<json object>))
回答by felixmosh
JSON.stringifyconverts new lines (\n) and tab (\t) chars into string, so, when you will try to parse it, the string will contain those again.
JSON.stringify将新行 ( \n) 和制表符 ( \t) 字符转换为字符串,因此,当您尝试解析它时,字符串将再次包含这些字符。
So, you need to search the string \n, you can do that with something like that.
所以,你需要搜索 string \n,你可以用类似的东西来做。
const stringWithNewLine = {
x: `this will conatin
new lines`
};
const json = JSON.stringify(stringWithNewLine);
console.log(json.replace(/\n/g, ''))

