Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
627 views
in Technique[技术] by (71.8m points)

javascript - 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!
]
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...