javascript JSON.stringify 输出之间的空格

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/24834812/
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

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-28 03:25:26  来源:igfitidea点击:

Space in between JSON.stringify output

javascriptjqueryhtmlarrays

提问by user3550203

I am using Jquery to get all products name from page and than put it on array. I am using this code

我正在使用 Jquery 从页面中获取所有产品名称,然后将其放在数组中。我正在使用此代码

 <script type="text/javascript">
 jQuery(document).ready(function($) {
    var products = $(".product-name").map(function() {
    return { name: $(this).text() }
 }) .get();
 console.log(JSON.stringify(products));
 });
 </script>

This give me output in this format

这给了我这种格式的输出

[{"name":"Sample Product Name"},{"name":"Sample Product Name 2"}]

[{"name":"示例产品名称"},{"name":"示例产品名称 2"}]

What I am trying to achieve is to have one space in between these two objects after "," so the output will look something like this

我想要实现的是在“”之后的这两个对象之间留一个空格,因此输出看起来像这样

[{"name":"Sample Product Name"}, {"name":"Sample Product Name 2"}]

[{"name":"示例产品名称"}, {"name":"示例产品名称 2"}]

Any advise? I am struggling from hours and no success.

有什么建议吗?我在几个小时内挣扎,但没有成功。

Here is the jsfiddle http://jsfiddle.net/2MeMY/1/

这是 jsfiddle http://jsfiddle.net/2MeMY/1/

回答by dave

This may not be what you want, but if you just want it to look better, I would recommend:

这可能不是你想要的,但如果你只是想让它看起来更好,我会建议:

console.log(JSON.stringify(products, null, 2));

which would give you

这会给你

[
  {
    "name": "Sample Product Name"
  },
  {
    "name": "Sample Product Name 2"
  }
]

In the console. If you really just want a space before commas, you could do:

在控制台中。如果你真的只想要逗号前的空格,你可以这样做:

console.log(JSON.stringify(products).split('},{').join('}, {'));

http://jsfiddle.net/2MeMY/3/

http://jsfiddle.net/2MeMY/3/

回答by Pratik Rathod

You can also do like this with replace

你也可以像这样替换

console.log(JSON.stringify(products).replace(/},{/g,'}, {')); 

// /},{/g means all occurance of },{

回答by Venryx

If you want a json-output that is:

如果您想要一个 json 输出:

  1. Single-line
  2. Has spaces between prop-names and prop-values (and between items)
  3. Has spaces between each comma and the next prop-name/item
  1. 单线
  2. 在道具名称和道具值之间(以及项目之间)有空格
  3. 每个逗号和下一个道具名称/项目之间有空格

You can use this:

你可以使用这个:

function Stringify_WithSpaces(obj) {
 let result = JSON.stringify(obj, null, 1); // stringify, with line-breaks and indents
 result = result.replace(/^ +/gm, " "); // remove all but the first space for each line
 result = result.replace(/\n/g, ""); // remove line-breaks
 result = result.replace(/{ /g, "{").replace(/ }/g, "}"); // remove spaces between object-braces and first/last props
 result = result.replace(/\[ /g, "[").replace(/ \]/g, "]"); // remove spaces between array-brackets and first/last items
 return result;
}

let obj = [{name: "Sample Product Name"}, {name: "Sample Product Name 2"}];
console.log("Stringified with spaces: " + Stringify_WithSpaces(obj));

And here's the function as a one-line expression:

这是作为单行表达式的函数:

JSON.stringify(obj, null, 1).replace(/^ +/gm, " ").replace(/\n/g, "").replace(/{ /g, "{").replace(/ }/g, "}").replace(/\[ /g, "[").replace(/ \]/g, "]")

Extended Typescript version

扩展打字稿版本



Here's a more verbose version (in Typescript) with options:

这是一个更详细的版本(在 Typescript 中),带有选项:

export class ToJSON_WithSpaces_Options {
    insideObjectBraces = false;
    insideArrayBrackets = false;
    betweenPropsOrItems = true;
    betweenPropNameAndValue = true;
}
export function ToJSON_WithSpaces(obj, options?: Partial<ToJSON_WithSpaces_Options>) {
    options = Object.assign({}, new ToJSON_WithSpaces_Options(), options);

    let result = JSON.stringify(obj, null, 1); // stringify, with line-breaks and indents
    result = result.replace(/^ +/gm, " "); // remove all but the first space for each line
    result = result.replace(/\n/g, ""); // remove line-breaks
    if (!options.insideObjectBraces) result = result.replace(/{ /g, "{").replace(/ }/g, "}");
    if (!options.insideArrayBrackets) result = result.replace(/\[ /g, "[").replace(/ \]/g, "]");
    if (!options.betweenPropsOrItems) result = result.replace(/, /g, ",");
    if (!options.betweenPropNameAndValue) result = result.replace(/": /g, `":`);
    return result;
}

Ideally, this sort of function will apply the regular-expressions priorto removing the line-breaks (so that it can guarantee it's not modifying text within user-supplied strings), but I'll leave that for someone else to do since the above is sufficient for my use-case (and I think most others).

理想情况下,这种函数将删除换行符之前应用正则表达式(以便它可以保证它不会修改用户提供的字符串中的文本),但我将把它留给其他人来做,因为上面足以满足我的用例(我认为大多数其他用例)。