26

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/

Stevoisiak
  • 23,794
  • 27
  • 122
  • 225
user3550203
  • 699
  • 1
  • 7
  • 15
  • Why do you want the output like this? JSON wasn't designed for humans to read all the time, so spending hours on spacing seems like a large waste of time. – Erik Philips Jul 18 '14 at 22:48
  • @ErikPhilips because at the system where I need to give the output is structured in such a way that it need the input like this :( [{"name":"Sample Product Name"}, {"name":"Sample Product Name 2"}] – user3550203 Jul 18 '14 at 22:54
  • 3
    So it's a non-standard based system, sorry that can't be fun. – Erik Philips Jul 18 '14 at 22:55
  • @ErikPhilips i had the same problem when working with APIGEE, trust me, it's not fun at all ! – Ariel Aug 19 '16 at 13:32

3 Answers3

41

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/

dave
  • 62,300
  • 5
  • 72
  • 93
1

You can also do like this with replace

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

// /},{/g means all occurance of },{
Pratik Rathod
  • 43
  • 1
  • 1
  • 7
  • While this code may answer the question, providing additional context regarding how and/or why it solves the problem would improve the answer's long-term value.[Read this](https://stackoverflow.com/help/how-to-answer). – Shanteshwar Inde Jan 30 '19 at 07:12
1

If you want a json-output that is:

  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

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:

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 prior to 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).

Venryx
  • 15,624
  • 10
  • 70
  • 96