您可以在JSON对象中使用尾随逗号吗? [英] Can you use a trailing comma in a JSON object?

查看:591
本文介绍了您可以在JSON对象中使用尾随逗号吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

当手动生成JSON对象或数组时,通常在对象或数组的最后一项上留下逗号是更容易的.例如,从字符串数组输出的代码可能看起来像(在C ++这样的伪代码中):

When manually generating a JSON object or array, it's often easier to leave a trailing comma on the last item in the object or array. For example, code to output from an array of strings might look like (in a C++ like pseudocode):

s.append("[");
for (i = 0; i < 5; ++i) {
    s.appendF("\"%d\",", i);
}
s.append("]");

给你一个像这样的字符串

giving you a string like

[0,1,2,3,4,5,]

可以吗?

推荐答案

不幸的是 JSON规范不允许尾随逗号.有几种浏览器可以使用它,但是通常您需要担心所有浏览器.

Unfortunately the JSON specification does not allow a trailing comma. There are a few browsers that will allow it, but generally you need to worry about all browsers.

通常,我会尝试解决问题,并在实际值前添加逗号,这样您最终会得到如下代码:

In general I try turn the problem around, and add the comma before the actual value, so you end up with code that looks like this:

s.append("[");
for (i = 0; i < 5; ++i) {
  if (i) s.append(","); // add the comma only if this isn't the first entry
  s.appendF("\"%d\"", i);
}
s.append("]");

for循环中多余的一行代码并不昂贵...

That extra one line of code in your for loop is hardly expensive...

从某种形式的字典将结构输出到JSON时,我使用的另一种替代方法是始终在每个条目之后添加一个逗号(如您在上面所做的那样),然后在没有尾随的末尾添加一个虚拟条目逗号(但这只是懒惰;->).

Another alternative I've used when output a structure to JSON from a dictionary of some form is to always append a comma after each entry (as you are doing above) and then add a dummy entry at the end that has not trailing comma (but that is just lazy ;->).

不幸的是,不适用于数组.

Doesn't work well with an array unfortunately.

这篇关于您可以在JSON对象中使用尾随逗号吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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