JavaScript JSON

JavaScript Tutorial

JavaScript JSON (JavaScript Object Notation)

JSON (JavaScript Object Notation) is a lightweight data format used for storing and transferring data between a server and a web application. It is easy for humans to read and easy for machines to parse.

Why JSON?

  • Language-independent (supported in almost all programming languages)

  • Commonly used in APIs and data exchange

  • Easy to read and write

  • Works perfectly with JavaScript objects

JSON Syntax Rules

RuleExample
Data is written in key/value pairs"name": "John"
Keys must be strings with double quotes"age"
Values can be string, number, boolean, null, array, or object"active": true
Object is wrapped {}{ "name": "John" }
Array is wrapped [][ "apple", "orange" ]

Example JSON Object

JSON vs JavaScript Object

FeatureJavaScript ObjectJSON
KeysNo quotes neededMust use double quotes
CommentsAllowed Not allowed
FunctionsAllowed Not allowed

Example difference:


 

Convert JSON to Js Object

Convert Js Object to JSON

 JSON with Arrays


 

 Unsupported Values in JSON

UnsupportedReason
FunctionsNot serializable
undefinedJSON cannot store it
Date object (becomes string)Requires conversion

Example Date handling:


 

 JSON with Fetch API Example (Real Use Case)

 Pretty Formatting JSON


 

 Summary

ConceptMethod
Parse JSON → ObjectJSON.parse()
Convert Object → JSONJSON.stringify()
Indent JSONJSON.stringify(obj, null, spacing)
Data Exchange formatAPI, localStorage, server

 Example: Store Data in LocalStorage Using JSON


 

You may also like...