简体   繁体   中英

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, 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!
]

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

I also faced the same problem in the velocity template.

You stated that the objects are dynamically inserted in the JSON. So most probably this should be the loop. So you can add the dummy object at the end of the loop.

Your velocity template should look like this:

   {
  "data": [
  #foreach($Student in $listStudent)
    {      
        "id" : "$Student.id"
        "Name" : "$Student.name"

    },
  #end
  {"_COMMENT":"THIS IS PLACED HERE JUST TO EGNORE TRAILING COMMA AT THE END OF LAST OBJECT",
   "_COMMENT":"THIS OBJECT MUST IGNORE WHILE PARSING"
  }
  ]
}

The only disadvantage of this trick is that you have to write some logic at the client end to avoid the dummy object while parsing the JSON object.

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

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

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 + "]";

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM