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

查看:39
本文介绍了您可以在 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("]");

给你一个字符串

[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天全站免登陆