Files and data

Distinguish JSON arrays, objects, and null

Use Array.isArray to recognize a JSON array and a separate null check for an object record. Typeof alone reports object for both arrays and null.

Worked example

Node.js example · save as example.mjs and run node example.mjs

for (const text of ['[]', '{}', 'null', '"text"']) {
  const value = JSON.parse(text);
  const kind = Array.isArray(value) ? "array"
    : value === null ? "null" : typeof value;
  console.log(kind);
}

How it works

The explicit classification prevents an importer from calling array methods on a wrapper object or reading fields from null. Inspecting the top-level structure is particularly useful when two export formats contain similar records under different containers.

Limits and mistakes

Recognizing an array says nothing about its element shapes. An object may still be an unexpected wrapper with a required nested list. Validate the format you support rather than accepting any structure that happens not to throw immediately.

Check the result

Expect array, object, null, string. Test representative complete export fixtures after top-level classification so the importer’s schema assumptions remain visible.

Sources

Reference documentation for the behavior used in this guide: