Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Space in between JSON.stringify output

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

 <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"}]

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"}]

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

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

like image 688
user3550203 Avatar asked Jul 18 '14 22:07

user3550203


People also ask

Does JSON Stringify remove spaces?

JSON. stringify(body) returns it without spaces.

Can you have spaces in JSON?

Format JSON files to be human readable. Use four spaces for indentation (matching OpenStack conventions used in Python and shell scripts). Do not use tab characters in the code, always use spaces.

How do I add a new line in JSON?

In JSON object make sure that you are having a sentence where you need to print in different lines. Now in-order to print the statements in different lines we need to use '\\n' (backward slash). As we now know the technique to print in newlines, now just add '\\n' wherever you want.

What is Stringify in JavaScript?

The JSON.stringify() method converts a JavaScript value to a JSON string, optionally replacing values if a replacer function is specified or optionally including only the specified properties if a replacer array is specified.


2 Answers

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/

like image 169
dave Avatar answered Sep 24 '22 06:09

dave


You can also do like this with replace

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

// /},{/g means all occurance of },{
like image 21
Pratik Rathod Avatar answered Sep 21 '22 06:09

Pratik Rathod