1

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",

1
  • "Text that's matched inside a non-capturing group is still consumed, the same as text that's matched outside of any group. A capturing group is like a non-capturing group with extra functionality: in addition to grouping, it allows you to extract whatever it matches independently of the overall match." - From: stackoverflow.com/questions/7505762/… Commented Jan 18, 2021 at 23:29

2 Answers 2

3

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);

Sign up to request clarification or add additional context in comments.

Comments

1
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

1 Comment

Thanks, but this does not work for me as it messes up the formatting for "b", which should come on a new line

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.