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

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

Is this allowed?

推荐答案

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.

一般来说,我会try 扭转这个问题,在实际值之前加上逗号,所以最终的代码如下所示:

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("]");

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

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

不幸的是,它不能很好地处理array.

Json相关问答推荐

使用SQL查询从SON中查找第n个密钥对值

输入请求中不存在null的条件抖动

Swift解码错误类型与`Bool`type不一致

我如何知道TJSONNumber是double还是double?

Bash和echo命令出现意外结果

当console.log返回TRUE值时,解析的JSON中的字段未定义

通过在织女星简化图上裁剪来显示文本

震动范围改善

VBA-JSON 嵌套集合解析为 Excel

如何将复杂的 JSON 反序列化为 Rust 类型?

在 CodePipeline 中调用 lambda 时传递用户参数

如何 Select 一个值,这是可选的 - 使用 jq

如何将从嵌套 Select 返回的空值转换为空数组?

如何将任意 json 对象发布到 webapi

有没有办法在 angular.json 中扩展配置?

ASP.NET Core API 仅返回列表的第一个结果

使用 application/json 优于 text/plain 的优势?

Jersey 2.0 相当于 POJOMappingFeature

从 JSON 中 Select 不同的值

我如何反序列化以杰克逊为单位的时间戳?