如何将 JSON 文档数组拆分为固定大小的块?

How to split an array of JSON documents into fixed size chunks?

我有一个 JSON 文档代表一个包含 100 个对象的数组,我需要批量处理这个文档,例如每批 10 个对象。

def text = '[{1st},{2nd},{3rd},{4th},...{100th}]'
def json = new groovy.json.JsonSlurper().parseText(text)

现在我需要从 text ([{1st},{2nd},..{10th}]) 和 post 中提取前 10 个元素到 Web 服务中,然后是另外 10 个 ([{11th},{12th}...{20th}]) 等等.

我在 C# 中尝试过,但在 Groovy 中无法做到。

有人建议我 send batches of json 的最佳方法,每次 json 的总数发生变化时 dynamically?

Groovy 通过 DefaultGroovyMethods class 添加 Iterable.collate(int size) 方法,您可以使用它将输入数组拆分为 n-size 块,例如

['a','b','c','d','e'].collate(3) == [['a','b','c'], ['d','e']]

考虑以下示例:

import groovy.json.JsonOutput
import groovy.json.JsonSlurper

final String text = '[{"id": 1}, {"id": 2}, {"id": 3}, {"id": 4}, {"id": 5}, {"id": 6}]'

final List<Map> json = new JsonSlurper().parseText(text) as List<Map>

json.collate(2).each { part ->
    final String out = JsonOutput.toJson(part)

    println "Sending following JSON object: ${out}"
}

Run in Groovy web console

这里我们有一个包含 6 个对象的 JSON 数组。我们将这个 JSON 解析为一个 List<Map> 对象,然后我们拆分成大小为 2 的块并准备 JSON 以供稍后执行。我只使用了 6 个对象作为示例,但是如果初始列表包含 100 个对象并且我们分成大小为 10 的块并不重要 - 算法是相同的。

可以按以下步骤概括和描述:

  1. 解析初始 JSON 对象数组
  2. 将数组拆分为大小为 10 的块
  3. 将 10 个对象的块格式化为 JSON 字符串
  4. 处理JSON文档

上面显示的示例产生以下输出:

Sending following JSON object: [{"id":1},{"id":2}]
Sending following JSON object: [{"id":3},{"id":4}]
Sending following JSON object: [{"id":5},{"id":6}]