I'm writing an API for retrieving data from a JDBC-connected Java Servlet via JSON. I've chosen to use JSON because we'll want to do sorts and other operations on the data in the browser, and we'll be accessing the data from across domains.

因为我基本上是在用JavaScript进行SQL查询,所以返回的数据本质上是表格式的.我开始写这篇文章,这样你可以得到一个列标签列表,然后是值数组,例如:

{
  "columns": [
    "given_name",
    "surname",
  ],
  "results": [
    [
      "Joe",
      "Schmoe"
    ],
    [
      "Jane",
      "Doe"
    ]
  ]
}

但是,当我开始编写JavaScript来处理返回的数据时,我想知道是否只输出带有键/值对的结果会更好,例如:

{
  "results": [
    {
      "given_name": "Joe",
      "surname": "Schmoe"
    },
    {
      "given_name": "Jane",
      "surname" : "Doe"
    }
  ]
}

如果你返回了很多结果,那就是很多重复的文本.但是我们将要传输Gzip,所以我不太关心带宽.

基本上,我应该设计这个,这样我就可以用

$.getJSON(query, function(data) {
  var columns = data.columns;
  var results = data.results;
  $.each(results, function(key, row) {
    console.log(row[columns.indexOf('surname')]);
  });
});

还是更漂亮

$.getJSON(query, function(data) {
  var results = data.results;
  $.each(results, function(key, row) {
    console.log(row.surname);
  });
});

?

从本质上说,我想知道对性能的潜在影响是否证明后一种选项的语法更加清晰.

Follow up

I did implement it both ways and profile. Profiling was a great idea! The differences in performance were marginal. The differences in data transfer size were substantial, but with Gzip compression, the variance was down to 5-6% between both formats and between very large and very small data sets. So I'm going with the prettier implementation. For this particular application, I can expect all clients to support Gzip/Deflate, so the size doesn't matter, and the computational complexity on both the client and server is similar enough that it doesn't matter.

For anyone interested, here is my data with graphs!.

推荐答案

综合其他答案:

  1. wire格式不必与内存格式相同.
  2. Profile which is better - see if it makes a difference.
  3. 通常,开始时越简单越好.

Further:

  • If you just have a page of results, and few users, then the 2nd format may be no worse than the 1st format.
  • If your data is quite sparse, the 2nd format may well be better.
  • 如果你正在发送may0行或may0行数据,并且你有数百万用户,那么你发送的数据的大小可能会开始起作用,也许第一种格式may会有所帮助.
  • 你不能保证所有的用户代理都支持gzip/deflate,所以要记住这一点.

Json相关问答推荐

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

为什么terraform不缩小这个策略JSON?'

Vega-Lite:文本笔画在外部

Jolt-Json转换:通过引用标识符(而不是索引)设置值

基于 JSON 字段的 Jolt 条件标志

为什么 Django Rest API 序列化器没有正确序列化多对多字段

Bicep脚本中如何设置弹性池的维护窗口?

将请求中的数据推送到数组中

将具有多个级别的 json 读入 DataFrame [python]

JOLT 在 struct 体中间添加一个 JSON 字段

jq:来自嵌套 JSON 的映射

如何在 powerapps 中将详细信息表单转换为 json?

Go - JSON 验证抛出错误,除非我在 struct 中使用指针.为什么?

如何从 rails 中的 respond_to 方法生成 json?

使用 simplejson 序列化简单类对象的最简单方法?

区分字符串和列表的 Pythonic 方式是什么?

如何使用 Jackson 注释从 HttpResponse 反序列化 JSON 对象?

使用 Python 3 读取 JSON 文件

使用 JSONArray 和 JSONObject 进行 Foreach

添加json文件注释