Skip to content
Talk to our solutions team

Batch-process JSON files with a script

Every JSON file in a directory passed through one script, with the results written where you choose.

A loop in a shell script works until it does not — and the ways it fails are all quiet.

Without thisWith this
A shell loop that stops at the first bad file, or does notEvery file processed, failures reported
Output overwrites input, so a re-run processes its own resultsSeparate directories, by default
Result shape differs from what the consumer expects--key nests it where the consumer looks
No record of what was processedA count and a per-file line

The entry point receives the parsed file:

function main(doc) {
return {
id: doc.id,
total: (doc.lines || []).reduce((s, l) => s + l.qty * l.price, 0)
};
}

Find the files, then fan out over them:

name: totals
tasks:
- name: find
glob:
pattern: "./orders/order-*.json"
setvar: files
next:
go: each
- name: each
map:
items_path: files
task: one
max_concurrency: 4
next:
go: done
- name: one
shell: "kis script run totals.js --debug < {{_item}}"
- name: done
succeed: true
Terminal window
kis flow -f totals.yaml -w 4

glob: collects the paths, map: runs the node once per path with {{_item}} bound to it, and max_concurrency bounds the parallelism. Give the run at least as many workers as the concurrency — with the default single worker, max_concurrency: 4 still runs one at a time.

Terminal window
kis script rules totals.js -i ./orders -o ./totals --pattern 'order-*.json'

Files not matching are skipped silently, which is convenient and worth remembering when the count is lower than you expected.

Replacing the document with the result is often not what a downstream consumer wants:

Terminal window
kis script rules totals.js -i ./orders -o ./totals --key computed

The result lands under computed rather than as the whole document, so the original content is preserved alongside it.

Facts and documents can be passed alongside each file:

Terminal window
kis script rules classify.js -i ./pages -o ./out \
--facts config=./rates.json \
--bbox page=./page-1.bbox.json
The jobUse
A one-off reshape of a directory you have in front of youScriptkis script rules is one command
Thousands of files, where a failure partway mattersFlow — the run names which items completed
It runs on a schedule, or someone else runs itFlow
The files are large enough that memory mattersA data pipeline — it streams
Terminal window
kis script rules totals.js \
--input ./orders \
--output ./totals \
--pattern 'order-*.json' \
--key computed \
--func main

Count in and out — they should match:

Terminal window
ls ./orders/order-*.json | wc -l
ls ./totals/*.json | wc -l

A shortfall means files failed or the pattern excluded them, and the run output distinguishes the two.