Pranav Shah
Pranav Shah

Reputation: 3323

Need help in formatting JSON (in JavaScript) with Stringify and Regex replace

I am missing something with the regex and it's removing the last letter of each item before the comma.

Sample code:

let test_json = { 
    "a" : { "a1" : "one", "is_active" : true, "a2" : "two" },
    "b" : { "b1" : "one", "is_active" : true, "b2" : "two" } 
}; 

JSON.stringify(test_json, null, 3).replace(/[^}],\n( )*"/g, ',   "');

The result is:

"{
   "a": {
      "a1": "one,   "is_active": tru,   "a2": "two"
   },
   "b": {
      "b1": "one,   "is_active": tru,   "b2": "two"
   }
}"

What I am trying to get is:

"{
   "a": {
      "a1": "one",   "is_active": true,   "a2": "two"
   },
   "b": {
      "b1": "one",   "is_active": true,   "b2": "two"
   }
}"

The things that are wrong:
"one, should be "one",
"tru, should be "true",

Upvotes: 1

Views: 67

Answers (2)

Ben Wainwright
Ben Wainwright

Reputation: 4611

Your problem is that you are finding the following sequence of characters

  • Any character that is not a closing brace
  • A comma
  • A newline character
  • Any number of spaces

And replacing the entire sequence. Since the "e" on the end of "true" is not a closing brace, it gets replaced as well.

What you need is for the first item in the sequence to be "a comma that comes immediately after a closing brace". You can do this using a negative lookbehind.

let test_json = {
  a: {
    a1: "one",
    is_active: true,
    a2: "two"
  },
  b: {
    b1: "one",
    is_active: true,
    b2: "two"
  },
};

const result = JSON.stringify(test_json, null, 3).replace(
  /(?<!}),\n\s*/g,
  ", "
);

console.log(result);

Upvotes: 3

MCP
MCP

Reputation: 117

JSON.stringify(test_json,null,3).replace(/([^}]?),\n( )*"/g, '$1,   "');

not sure of it's the best way but it's the first thing that came to mind

Upvotes: 1

Related Questions