Overview
This lecture introduces JSON (JavaScript Object Notation), explaining what it is, why it's important for web development, its syntax, and practical examples of creating and using JSON data.
What is JSON and Why Use It?
- JSON stands for JavaScript Object Notation and is a lightweight data representation format.
- It is widely used in APIs, configuration files, games, and text editors due to its simplicity and small file size.
- JSON is easy to read and integrates well with JavaScript, making it popular in web development.
- Major programming languages can parse JSON strings into usable objects.
JSON Data Types and Syntax
- JSON supports data types: strings, numbers (including decimals, negatives, scientific), booleans (true/false), null, arrays, and objects.
- A JSON object uses curly braces
{} and contains key-value pairs, where keys and string values must be in double quotes.
- Arrays use square brackets
[] and can contain any supported JSON type, including objects and other arrays.
- Keys in objects must always be wrapped in double quotes, and commas separate each key-value pair.
JSON Example Structure
- Typically, JSON files start with an object or an array as the top-level structure.
- Deeply nested data is possible by placing arrays or objects inside objects or arrays.
- Example: A user object might have keys for name (string), favorite number (number), isProgrammer (boolean), hobbies (array), and friends (array of objects).
Creating and Using JSON Files
- Create a JSON file by saving it with a
.json extension.
- Example JSON array of companies: each company is an object with keys for name, number of employees, CEO, and rating.
- Null values are allowed for keys when data is absent (e.g., no CEO).
- Proper JSON formatting requires double quotes for keys/strings and careful comma placement.
Parsing and Using JSON in JavaScript
- JSON data can be imported directly into JavaScript as valid objects or as strings.
- To convert a JSON string to a JavaScript object, use
JSON.parse(string).
- Once parsed, object properties can be accessed just like any regular JavaScript object.
Key Terms & Definitions
- JSON (JavaScript Object Notation) — A text-based data format for representing structured data.
- Object — A collection of key-value pairs, enclosed in curly braces.
- Array — An ordered list of values, enclosed in square brackets.
- Boolean — A data type with two possible values: true or false.
- Null — A special value representing "nothing" or "no value".
- JSON.parse() — JavaScript function that converts a JSON string into an object.
Action Items / Next Steps
- Practice creating a
.json file and writing objects and arrays.
- Try parsing a JSON string into a JavaScript object using
JSON.parse().
- Review proper JSON syntax, especially double quotes and comma placement.