What is JSON?
JavaScript Object Notation (JSON) is a minimal, readable format for structuring data. It is used primarily to transmit data between a server and web application, as an alternative to XML.
JSON Example
{
"name": "John Doe",
"age": 30,
"email": "john@example.com",
"isActive": true,
"hobbies": ["reading", "hiking", "coding"],
"address": {
"street": "123 Main St",
"city": "New York",
"zipCode": "10001"
}
}Understanding JSON
JSON (JavaScript Object Notation) is a lightweight data-interchange format that is easy for humans to read and write, and easy for machines to parse and generate.
JSON is derived from JavaScript object notation syntax, but it is a language-independent data format. Code for parsing and generating JSON data is readily available in many programming languages.
The main advantage of JSON over XML is that it is more compact, faster to parse, and easier for humans to write and read.
JSON Syntax Rules
- •Data is in name/value pairs
- •Data is separated by commas
- •Curly braces hold objects
- •Square brackets hold arrays
- •Keys must be strings, enclosed in double quotes
- •Values can be strings, numbers, booleans, null, objects, or arrays
JSON Data Types
String
A sequence of characters enclosed in double quotes
"Hello World"
Number
Integer or floating point numbers
42 or 3.14
Boolean
True or false values
true or false
Null
Represents a null value
null
Object
A collection of name/value pairs enclosed in curly braces
{"name": "John", "age": 30}Array
An ordered list of values enclosed in square brackets
["apple", "banana", "orange"]
JSON vs XML
Working with JSON in JavaScript
JSON.parse()
Converts a JSON string into a JavaScript object
JSON.stringify()
Converts a JavaScript object into a JSON string
JSON Best Practices
- •Use double quotes for keys and string values
- •Avoid trailing commas
- •Use proper indentation for readability
- •Keep JSON structures simple and flat when possible
- •Always validate JSON before parsing or using it
- •Be careful with sensitive data in JSON