JSON (JavaScript Object Notation)
JSON (pronounced "Jason") is a data interchange format for storing and exchanging information.
The format represents data using curly braces { } or square brackets [ ], comprising pairs of keys (in double quotes) and values that can be strings, numbers, etc.
{ "name": "CodeBuddies", "address": { "city": "New York" }, "age": 20 }
Multiple key-value pairs can be listed using commas (,) between them, and no comma follows the last pair.
JSON is structured based on the way objects are created in JavaScript, but it is language-independent and can be used with most programming languages.
It's widely used for data interaction between a server and web pages in most applications.
Basic Structure of JSON
JSON is characterized by being represented only as an object or an array.
1. Object
A collection of key-value pairs enclosed in curly braces { }.
{ "key1": "value1", "key2": "value2", ... }
{ "name": "CodeBuddies", "age": 25 }
2. Array
A list of values enclosed in square brackets [ ].
["value1", "value2", "..."]
["apple", "banana", "cherry"]
Handling JSON in JavaScript
JavaScript natively provides the JSON object to handle JSON data.
The JSON object provides methods to convert JSON data to a string or to a JavaScript object.
1. JSON.stringify()
Converts JavaScript objects or values to a JSON string.
const obj = { name: 'CodeBuddies', age: 25, }; const jsonString = JSON.stringify(obj); console.log(jsonString); // Prints '{"name":"CodeBuddies","age":25}'
2. JSON.parse()
Converts a JSON string to a JavaScript object or value.
const jsonString = '{"name":"CodeBuddies","age":25}'; const obj = JSON.parse(jsonString); console.log(obj.name); // Prints "CodeBuddies"
Important Points
-
Keys used as property names in JSON must always be enclosed in double quotes ("). JavaScript objects allow single quotes ('), but JSON does not permit single quotes.
-
Data types not supported by JSON (e.g., functions,
undefined) cannot be converted to JSON.
Lessons in this chapter · How does JavaScript work in the browser?
- 1. How Do Browsers Work?
- 2. DOM (Document Object Model)
- 3. Browser Window Object
- 4. Window - window.screen
- 5. Window - window.location
- 6. Methods to Select HTML Elements - 1
- 7. How to Select HTML Elements - 2
- 8. Creating and Setting Attributes of HTML Elements
- 9. Events
- 10. Advanced Event Handling
- 11. Multiple-choice quiz
- 12. JSON(JavaScript Object Notation)
- 13. Promise
- 14. Async/Await Handling Asynchronous Processes
- 15. Cookies
- 16. Multiple-choice quiz
- 17. JavaScript Summary
In JSON format, keys must always be enclosed in single quotes (').
Lecture
AI Tutor
Design
Upload
Notes
Favorites
Help