NEWStandard createTask and in.php APIs. Change the address and you are connected.View API docs
GATESOLVER

Web scraping

How do I handle nested JSON in JavaScript?

Parse once, then read deep fields with optional chaining (?.) and defaults (??), flatten nested lists with flatMap, and use a recursive search when you do not know where a key lives.

The short answer

After JSON.parse or await response.json(), nested JSON is just objects inside objects. The safe way to read a deep value is optional chaining with a default: data.product?.offers?.[0]?.price ?? null. It returns null instead of throwing when any level is missing. For lists inside lists, flatMap turns them into one flat array of records you can store or export.

Reading deep values without crashing

Scraped JSON is inconsistent: a field exists on one item and not the next, an array is empty, a value is null. Plain dot access throws TypeError: Cannot read properties of undefined at the first gap. Optional chaining stops at the gap instead:

const listing = await res.json();

const city    = listing.location?.address?.city ?? "unknown";
const firstPic = listing.media?.photos?.[0]?.url ?? null;
const rating  = listing.reviews?.summary?.score ?? null;
const tags    = listing.meta?.tags ?? [];

Use ?? rather than || for defaults. || also replaces 0, empty strings and false, which are real values: a price of 0 or a stock count of 0 would silently become your default.

Flattening nested arrays into rows

APIs often return categories that contain products that contain variants. To get one row per variant, chain flatMap and carry the parent fields down:

const rows = payload.categories.flatMap((cat) =>
  (cat.items ?? []).flatMap((item) =>
    (item.variants ?? []).map((v) => ({
      category: cat.name,
      itemId: item.id,
      title: item.title,
      sku: v.sku,
      size: v.attributes?.size ?? null,
      inStock: Boolean(v.stock?.available),
    }))
  )
);

The result is a flat array of objects with the same keys, ready for a CSV writer or a database insert. The question on converting JSON to CSV takes it from there.

Finding a key when you do not know the path

Sites that embed state in the page, such as a __NEXT_DATA__ script or a large Redux store, bury useful fields at varying depths. A recursive search collects every match with its path, which you can then hard-code once you understand the shape:

function findKey(node, wanted, path = "$", out = []) {
  if (node && typeof node === "object") {
    for (const [prop, v] of Object.entries(node)) {
      const here = Array.isArray(node) ? `${path}[${prop}]` : `${path}.${prop}`;
      if (prop === wanted) out.push({ path: here, value: v });
      findKey(v, wanted, here, out);
    }
  }
  return out;
}
console.log(findKey(stateBlob, "priceAmount").slice(0, 5));

Normalizing types as you read

Nested JSON from different endpoints of the same site often disagrees on types: a price is a number in one place and a string such as "19.90" in another, a date is an ISO string here and a Unix timestamp there. Convert at the moment you read the field, inside the mapping function, so every record leaving it has one type per key. Number(v.price) plus a check with Number.isFinite catches values that do not convert, and logging those with their path tells you exactly where the API differs.

Destructuring with defaults

When you read several fields from the same level, destructuring keeps code compact: const { title = "", brand: { name: brandName } = {} } = item;. The = {} on the nested part prevents a crash when brand is missing. It reads well for two or three levels; for anything deeper, optional chaining is easier to follow.

Validate the shape you rely on

When a site changes its API, optional chaining keeps your script running but fills your data with nulls. Add a cheap check after parsing: count how many records have the key fields, and stop the run if the share drops sharply compared with the last run. For larger projects, a schema library such as Zod or Ajv can describe the expected shape and report exactly which field changed. That turns a silent data loss into a clear error message.

Common mistakes

  • Parsing twice. response.json() already returns an object; calling JSON.parse on it fails.
  • Escaped JSON inside JSON. Some APIs put a JSON string in a field. Parse that field a second time.
  • Large numbers. Ids above 2^53 (about nine quadrillion) lose precision as numbers. If an API returns long numeric ids, prefer their string form when one is offered.
  • Mutating shared objects. Copy with structuredClone before editing if the same data feeds several steps.

Where the JSON comes from matters

If a JSON endpoint suddenly returns HTML, your parse fails with "Unexpected token <". That usually means a login page, an error page or a bot check replaced the response. Log the first few hundred characters of any body that fails to parse. For APIs behind a CAPTCHA wall, see hidden API scraping and the GateSolver docs.

Common questions

What does ?. do in JavaScript?

It is optional chaining: it returns undefined instead of throwing when the value before it is null or undefined.

Should I use ?? or || for default values?

Use ??, which only replaces null and undefined. || also replaces 0, empty strings and false.

How do I flatten nested arrays of objects?

Use flatMap at each level and copy parent fields into each child record.

Why do I get Unexpected token < in JSON?

The response is HTML, often an error or challenge page, not JSON. Check the status and content type.

How do I find where a field sits in a huge JSON blob?

Run a recursive search that records the path of every matching key, then use that path directly.

Keep reading