JSON从最后一个对象中删除尾随逗号 [英] JSON Remove trailiing comma from last object

查看:562
本文介绍了JSON从最后一个对象中删除尾随逗号的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

此JSON数据正在动态插入到我正在处理的模板中.我正在尝试从对象列表中删除结尾的逗号.

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.

我正在使用的CMS使用Velocity,但我还不太熟悉.因此,我希望编写一段JavaScript代码,以检测最后一个对象(ITEM2)上的尾随逗号并将其删除.在该右括号之前是否可以使用REGEX来检测任何逗号?

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

推荐答案

您需要找到,,此后没有任何新的属性,对象或数组.
新属性可以以引号("')或任何单词字符(\w)开头.
新对象只能以字符{开头.
新数组只能以字符[开头.
新属性,对象或数组可以放在一堆类似空格的符号(\s)之后.

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;

像这样使用它:

// 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)之后.

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

因此正则表达式:

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

用法相同.

尝试第二个正则表达式.

这篇关于JSON从最后一个对象中删除尾随逗号的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆