Lecture

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.

JSON Example
{ "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 { }.

JSON Object Format
{ "key1": "value1", "key2": "value2", ... }
JSON Object Example
{ "name": "CodeBuddies", "age": 25 }

2. Array

A list of values enclosed in square brackets [ ].

JSON Array Format
["value1", "value2", "..."]
JSON Array Example
["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.

JSON.stringify() Example
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.

JSON.parse() Example
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.

Mission
0 / 1

In JSON format, keys must always be enclosed in single quotes (').

True
False

Lecture

AI Tutor

Design

Upload

Notes

Favorites

Help

HTML
CSS
JavaScript
Loading...