Skip to content Skip to sidebar Skip to footer

Json Remove Trailiing Comma From Last Object

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

Solution 1:

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:

// javascriptlet input; // this is the initial string of datalet correct = input.replace(regex, ''); // remove all trailing commaslet 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.

Solution 2:

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

Solution 3:

I developped a simple but useful logic for this purpose - you can try this.

IntegerCnt=5;
        StringStrInput="[";
        
        for(int i=1; i<Cnt; i++){
            StrInput+="   {"+"     \"ITEM"+i+"\":{ "+"      \"names\":["+"   \"nameA\""+"]"+"}";
                            
            if(i ==(Cnt-1)) { 
                StrInput+="}";            
            } else {
                StrInput+="},";
            }
        
        }
        StrInput+="]";
        
        System.out.println(StrInput);

Solution 4:

Consider the Json input = [{"ITEM1":{"names":["nameA"]}},{"ITEM2":{"names":["nameB","nameC"]}},] without whitespaces. I suggest a simple way using substring.

input = input.substring(0, input.length-2);input = input + "]";

Post a Comment for "Json Remove Trailiing Comma From Last Object"