ometimes you get a huge JSON array, a few thousand records in one file, and you need it in smaller pieces. Maybe an API only accepts 500 items at a time, or your editor chokes on the file.
The easy way is to paste it into an online tool. But if the data is private, uploading it to a random server isn't a great idea. Here is how to do it entirely in the browser.
The idea
Parse the JSON, cut the array into groups of N items, and turn each group back into text.
function splitArray(arr, size) {
const parts = [];
for (let i = 0; i < arr.length; i += size) {
parts.push(arr.slice(i, i + size));
}
return parts;
}
const data = JSON.parse(text); // text = your file contents
const parts = splitArray(data, 500); // 500 items per part
Splitting an object instead of an array
If the top level is an object, split its keys instead:
function splitObject(obj, size) {
const keys = Object.keys(obj);
const parts = [];
for (let i = 0; i < keys.length; i += size) {
const chunk = {};
keys.slice(i, i + size).forEach(k => { chunk[k] = obj[k]; });
parts.push(chunk);
}
return parts;
}
Saving each part as a file
Browsers can create a download from a Blob, with no server involved:
function download(name, value) {
const blob = new Blob([JSON.stringify(value, null, 2)], { type: 'application/json' });
const a = document.createElement('a');
a.href = URL.createObjectURL(blob);
a.download = name;
a.click();
URL.revokeObjectURL(a.href);
}
parts.forEach((p, i) => download(`part-${i + 1}.json`, p));
One catch: many browsers block several downloads fired at once, so it is safer to give each part its own download button.
A few things to watch for
-
Invalid JSON.
JSON.parsethrows on bad input, so wrap it intry/catchand show the error message to the user. - Very large files. Everything is held in memory, so a file of many megabytes can make the tab slow. For huge files, a streaming parser or a command-line tool is a better fit.
-
Order. Items keep their original order, so you can join the parts back together later with
concat.
If you don't want to write code
I put this into a small free tool: JSON Splitter. Paste your JSON, choose how many items per part, then copy or download each part. It runs fully in your browser, and nothing you paste is uploaded.
It is part of Parsekit, a set of small JSON utilities that all run client-side: formatter, JSON to CSV and YAML, merge, diff, splitter, escape/unescape, Base64 and URL encode/decode. The site uses Google Analytics for basic page-view counts, but it never sees what you paste.
I'd love to hear which tool you'd want next, or if something breaks on an edge-case JSON file.
Top comments (0)