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/
JSON. stringify(body) returns it without spaces.
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.
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.
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.
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/
You can also do like this with replace
console.log(JSON.stringify(products).replace(/},{/g,'}, {'));
// /},{/g means all occurance of },{
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With