Reputation: 3323
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
Reputation: 4611
Your problem is that you are finding the following sequence of characters
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
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