This JSON data is being dynamically inserted into a template I'm working on. I'm trying to remove the trailing comma from the list of objects.
The CMS I'm working in uses Velocity, which I'm not too familiar with yet. So I was looking to write a snippet of JavaScript that detects that trailing comma on the last object (ITEM2) and removes it. Is there a REGEX I can use to detect any comma before that closing bracket?
[
{
"ITEM1":{
"names":[
"nameA"
]
}
},
{
"ITEM2":{
"names":[
"nameB",
"nameC"
]
}
}, // need to remove this comma!
]
Trailing commas in JSON As JSON is based on a very restricted subset of JavaScript syntax, trailing commas are not allowed in JSON.
Hold an int (without commas) and then format the output of this int to include commas, when you output it.
A trailing comma, also known as a dangling or terminal comma, is a comma symbol that is typed after the last item of a list of elements. Since the introduction of the JavaScript language, trailing commas have been legal in array literals. Later, object literals joined arrays.
You need to find ,
, after which there is no any new attribute, object or array.
New attribute could start either with quotes ("
or '
) or with any word-character (\w
).
New object could start only with character {
.
New array could start only with character [
.
New attribute, object or array could be placed after a bunch of space-like symbols (\s
).
So, the regex will be like this:
let regex = /\,(?!\s*?[\{\[\"\'\w])/g;
Use it like this:
// javascript
let input; // this is the initial string of data
let correct = input.replace(regex, ''); // remove all trailing commas
let data = JSON.parse(correct); // build a new JSON object based on correct string
Try the first regex.
Another approach is to find every ,
, after which there is a closing bracket.
Closing brackets in this case are }
and ]
.
Again, closing brackets might be placed after a bunch of space-like symbols (\s
).
Hence the regexp:
let regex = /\,(?=\s*?[\}\]])/g;
Usage is the same.
Try the second regex.
For your specific example, you can do a simple search/replace like this:
,\n]$
Replacement string:
\n]
Working demo
Code
var re = /,\n]$/;
var str = '[ \n { \n "ITEM1":{ \n "names":[ \n "nameA"\n ]\n }\n },\n { \n "ITEM2":{ \n "names":[ \n "nameB",\n "nameC"\n ]\n }\n },\n]';
var subst = '\n]';
var result = str.replace(re, subst);
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