JSON Remove trailing comma from last object

JSON data is dynamically inserted into the template I'm working on. I am trying to remove a trailing comma from a list of objects.

The CMS I work for uses Velocity, which I am not familiar with yet. So I wanted to write a piece of JavaScript that detects this trailing comma on the last object (ITEM2) and removes it. Is there a REGEX that I can use to detect any comma before this closing bracket?

[  
   {  
      "ITEM1":{  
         "names":[  
            "nameA"
         ]
      }
   },
   {  
      "ITEM2":{  
         "names":[  
            "nameB",
            "nameC"
         ]
      }
   }, // need to remove this comma!
]
+4
source share
3 answers

, , .
(" '), (\w).
{.
[.
, , (\s).

, :

let regex = /\,(?!\s*?[\{\[\"\'\w])/g;

:

// 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

.


, .
} ].
, , (\s).

:

let regex = /\,(?=\s*?[\}\]])/g;

.

.

+11

/ :

,\n]$

:

\n]

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

.

, JSON. , , . , .

Your speed 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 drawback to this trick is that you need to write some client-side logic to avoid a dummy object when parsing a JSON object.

0
source

Source: https://habr.com/ru/post/1620638/


All Articles