学习库JavaScriptJSON and Data Validation

JSON and Data Validation

Serialize supported values and validate external data before trusting its shape.

更新于 适用于 ECMAScript 2026 and JSON

JSON is a text format for objects, arrays, strings, numbers, booleans, and null. It does not preserve functions, undefined, symbols, Map, Set, or class identity.

Parse and stringify

json.js
const payload = JSON.stringify({ course: "JavaScript", complete: false });

let value;
try {
  value = JSON.parse(payload);
} catch {
  throw new Error("Response was not valid JSON");
}

Parsing confirms syntax, not meaning. External data can still have missing properties or incorrect types.

Validate the boundary

validate.js
function isCourse(value) {
  return typeof value === "object" && value !== null
    && typeof value.title === "string"
    && Number.isInteger(value.lessonCount)
    && value.lessonCount >= 0;
}

if (!isCourse(value)) throw new TypeError("Invalid course response");

For larger systems, use a schema validator and derive static types from the same schema when possible.

Keep this

Know what JSON can represent, handle syntax errors, and validate shape before data enters the rest of the application.

学习位置已保存在此设备上。