如何从JSON.stringify中删除转义序列,以便它是人类可读的? [英] How can I remove escape sequences from JSON.stringify so that it's human-readable?
问题描述
当我在JavaScript中的复杂对象上调用JSON.stringify()时,它会生成一个包含大量转义序列的字符串(\,\\等)。
When I call JSON.stringify() on a complex object in JavaScript, it produces a string with lots of escape sequences (\", \\", etc.).
如何让它创建一个人类可读的JSON字符串呢?即,您可以复制/粘贴到网络上的许多JSON验证器之一?
How can I make it create a human-readable JSON string instead? I.e., one that you can copy/paste into one of the many JSON validators on the web?
为了澄清,我的第一个问题是删除转义序列。
To clarify, my #1 concern is removing the escape sequences.
推荐答案
您可以使用替换者。 JSON.stringify.Replacer提供的第二个参数可以是函数或数组。
You can use the replacer. The second parameter provided by JSON.stringify.Replacer could be a function or array.
在您的情况下,我们可以创建一个用空格替换所有特殊字符的函数。下面的例子替换了空格和下划线。
In your case we can create a function which replaces all the special characters with a blank space.The below example replaces the whitespaces and underscores.
function replacer(key, value) {
return value.replace(/[^\w\s]/gi, '');
}
var foo = {"a":"1","b":2};
var jsonString = JSON.stringify(foo, replacer);
如果您只是想替换一个特殊字符,请使用:
If you simply want to replace the one special character, use:
JSON.stringify({ a: 1, b: 2 }, null, '\t');
有关替换者的更多信息,请查看MDN页 JSON.stringify() 。
For more information on replacer, check the MDN page JSON.stringify().
这篇关于如何从JSON.stringify中删除转义序列,以便它是人类可读的?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!