Reference article · Programming
JSON: format, parsing and data validation
JSON is a text format for exchanging data, commonly used in configuration files and API responses. JSON text and an object in memory are different things.
Supported values
JSON supports objects, arrays, strings, numbers, booleans and null. Property names and strings require double quotes. Comments, trailing commas, functions and undefined are unsupported. Dates are often strings interpreted according to an application contract.
{
"title": "Introduction to HTML",
"published": true,
"tags": ["web", "beginner"],
"visits": 0,
"author": null
}From text to values and back
JSON.parse interprets text; JSON.stringify turns a compatible value into JSON text. stringify’s third argument can add indentation.
const text = '{"title":"HTML","visits":0}';
const article = JSON.parse(text);
console.log(article.title); // HTML
console.log(JSON.stringify(article, null, 2));Valid syntax is not valid application data
"hello" is valid JSON, but not an article record. Check the resulting type and the fields your program requires.
function isArticle(value) {
return value !== null
&& typeof value === "object"
&& !Array.isArray(value)
&& typeof value.title === "string"
&& Number.isInteger(value.visits)
&& value.visits >= 0;
}Parsing failures
Invalid syntax makes JSON.parse throw SyntaxError. Catch malformed input and provide a useful message. Reading JSON does not require executing text with eval. The example checks two fields, not a complete schema.
Practice
- Check the example record with isArticle; expect true.
- Change visits to "0"; expect false.
- Try null and an array; neither fits the expected record.
References
Related articles
- Fundamentals: variables, conditions and loops
- Semantic HTML and page structure
- CSS: box model, Flexbox and Grid
- JavaScript: functions, parameters and scope
- JavaScript: arrays, objects and data transformations
- DOM and events: connect JavaScript to HTML
- Promises, async/await and fetch requests
- HTTP and web APIs: requests, responses and status codes
- Git: changes, commits, branches and remotes
- Node.js and npm: project scripts and dependencies
- Debugging and tests: finding and checking errors
- Colour formats: HEX, RGB and HSL
- UUID identifiers
- Random values in JavaScript
