
- JSON - Home
- JSON - Overview
- JSON - Syntax
- JSON - DataTypes
- JSON - Objects
- JSON - Schema
- JSON - Comparison with XML
- JSON Useful Resources
- JSON - Quick Guide
- JSON - Cheatsheet
- JSON - Useful Resources
- JSON - Discussion
JSON Cheatsheet
In this cheatsheet, we will cover the JSON Cheatsheet, providing a quick reference to understand and use JSON effectively. JSON (JavaScript Object Notation) is a lightweight, text-based format for data exchange, widely used in web development for storing and transmitting data between servers and clients.
Table of Contents
- What is JSON?
- Basic JSON
- JSON Examples
- JSON Data Types
- Special Characters
- Arrays
- Objects
- Accessing JSON Data
- Syntax and Structure
- Parsing Techniques
- Validation
- Performance Optimization
What is JSON?
JSON full form is JavaScript Object Notation. It is a lightweight data-interchange format that is Stands for, It is easy for humans to read and write. Reading and generation are friendly to machines. JSON is used in a standard way to transfer information between a server and a client.
Main Features
- Text-based format.
- Few, but important: independent of the language, but based on conventions C-like languages (C, Java, Js, Python, etc.)
- Best used for organizing and moving information from one place to another.
Basic JSON
Basic JSON is a simple, human-readable format for storing and exchanging data. It uses a key-value pair structure to represent data, making it easy to transmit between servers and clients in web applications.
Flat Object
These are enclosed in curly braces {} and contain key-value pairs.
{ "name": "Sam", "age": 25, "isMarried": false }
Simple Array
Arrays are ordered lists enclosed in square brackets [].
["Pineapple", "Blackberry", "Mango"]
Object with a Single Array
An object with a single array in JSON consists of a key-value pair, where the value is an array containing multiple items.
{ "hobbies": ["reading", "traveling", "swimming"] }
Key-Value Pairs
The Key-value pairs in JSON represent data where each key is a unique identifier, and the value can be a string, number, object, array, or boolean.
{ "id": 101, "status": "active" }
JSON Example 1
{ "superheroes": { "hero": [ { "id": "1", "firstName": "Fast", "lastName": "Kick" }, { "id": "2", "firstName": "Hawk", "lastName": "Storm" } ] } }
JSON Example 2
{ "name": "Ram", "age": 23, "gender": "M", "salary": 40000, "married": true, "children": [ { "name": "Sam", "age": 26, "gender": "M" }, { "name": "Sita", "age": 18, "gender": "F" } ] }
JSON Data Types
Following are the data types that JSON format supports −
Type | Illustration | Example |
---|---|---|
Number | Double precision floating-point | 23, 40000, 0.5 |
String | A sequence of one or more characters enclosed in single quotes | "name": Ram |
Boolean | true or false | true, false |
Array | Ordered sequence of values | ["a", "b", "c"] |
Object | An associative array, such as storage, doesnt have an implicit order for storing the key/value pairs. | "key": "value" |
null | Meaning it is an empty or undefined value | null |
Special Characters
The table shows various special characters that you can use in strings of a JSON document
String | Illustration |
---|---|
\" | Double quote |
\/ | Forward slash |
\b | Backspace |
\\ | Backslash |
\u | Unicode escape sequence |
\n | Newline |
\f | Form feed |
\r | Carriage return |
\t |
Tab |
Array
Arrays are ordered lists that are enclosed in square brackets, like this: [].
Basic Array
["apple", "banana", "mango"]
2D Array
2D ARRAY is used to organize data in a matrix-like format, with rows and columns, allowing for the representation of complex datasets such as tables or grids.
{ "my_sequences": [ [1, 2, 3], [4, 5, 6], [7, 8, 9, 0], [10, 11] ] }
Array of Objects
An object in JSON consists of a key-value pair, where the value is an array containing multiple items.
{ "children": [ { "name": "Jimmy Smith", "age": 15 }, { "name": "Sammy Sosa", "age": 12 } ] }
OBJECT
JSON objects can be created with JavaScript.
Nested Object
Nested objects in JSON refer to objects within other objects, allowing complex data structures. They are defined using curly braces {} and can contain key-value pairs, where values may also be objects or arrays.
{ "Alex": { "id": 7, "fullName": "Smith", "income": 30000, "hobbies": ["reading", "traveling"], "location": { "country": "X", "city": "X-City" } } }
Object of Arrays
{ "attributes": ["a1", "a2"], "methods": ["getter", "setter"], "empty_array": [] }
Object of Objects
An object of objects in JSON is a structure where the value of a key is another object. This allows for organizing data hierarchically, with each key pointing to a nested object.
{ "Mark McGwire": { "hr": 65, "avg": 0.278 }, "Sammy Sosa": { "hr": 63, "avg": 0.288 } }
Object Containing Arrays
An object containing arrays in JSON consists of key-value pairs where the values are arrays. These arrays can store multiple elements, such as strings, numbers, or other objects, allowing for structured and flexible data representation.
{ "features": ["feature1", "feature2"], "actions": ["read", "write"], "emptyList": [] }
Object Containing Objects
{ "Babe Ruth": { "homeRuns": 59, "average": 0.342 }, "Joe DiMaggio": { "homeRuns": 46, "average": 0.352 } }
Accessing JSON Data
Accessing JSON data involves using keys to retrieve values from an object or array. In most programming languages, this can be done using dot notation or bracket notation to access nested elements.
Access Object
Accessing an object in JavaScript involves using either dot notation (object.key) or bracket notation (object["key"]).
let person = { "firstName": "Michael", "lastName": "Brown", "age": 34, "gender": "M", "income": 85000, "isMarried": true }; person.firstName // "Michael" person["lastName"] // "Brown" person.age // 34 person.other // undefined person[0] // undefined
Access Array of Objects
To access an array of objects in JavaScript, you would typically reference the object first and then access its properties using dot or bracket notation.
let myObj = { "name": "John", "age": 36, "married": true }; console.log(myObj.name); // Output: John console.log(myObj.age); // Output: 36
Access Array
To access elements in an array, you use the index of the element, starting from 0. In the provided example, myArray[0] accesses the first element "John", and myArray[3] accesses the fourth element 36.
let myArray = ["John", "Doe", 69000, 36, "M", true]; console.log(myArray[0]); // Output: John console.log(myArray[3]); // Output: 36
Access Nested Data
To access nested data in an object or array, you use dot notation for objects and array indexing for arrays. In your example, myObj.tsmith[2] accesses the third element (42) from the array stored in the tsmith key.
let myObj = { "ref": { "name": 0, "last": 1, "age": 2 }, "jdoe": ["John", "Doe", 39], "tsmith": ["Tom", "Smith", 42] }; console.log(myObj.ref.last); // Output: 1 console.log(myObj.tsmith[2]); // Output: 42
JSON Numbers
JSON format supports the following number types
Type | Example |
---|---|
Integer | {"value": 24} |
Negative | {"value": -8} |
Exponent | {"value": 2.0E+3} |
Fraction | {"value": 0.6} |
Zero | {"value": 0} |
Syntax and Structure
The following are the syntax and structure for JSON in JavaScript
Component | Explanation | Example |
---|---|---|
Data Object | Key-value pairs inside {} | { "name": "Ram" } |
Data List | Values inside [] | [ "cat", "dog" ] |
Key-Value Pair | Key and value are separated by : | "city": "Kolkata" |
Text Value | Characters in double quotes " | "Hello" |
Numeric Value | Numbers without quotes | 50, 2.15 |
Logical Value | Boolean true or false. | true, false |
Empty Value | Represents no data. | null |
Embedded Object | The object within another object. | "address": { "city": "KL" } |
Embedded List | Array within another array. | "nums": [[1, 2], [3, 4]] |
Parsing Techniques
Parsing techniques in JSON involve converting JSON strings into JavaScript objects using JSON.parse() and vice versa using JSON.stringify().
Basic Parsing
Basic parsing in JSON involves converting a properly formatted JSON string into a JavaScript object using JSON.parse().
const obj = JSON.parse('{"name":"Ram", "age":25, "city":Kolkata"}'); console.log(obj.name); // Output: Ram
Parsing JSON Arrays
Parsing JSON arrays is done using JSON.parse(), which converts a JSON string representing an array into a JavaScript array.
const text = '["Ford", "BMW", "Ferrari", "TATA"]'; const myArr = JSON.parse(text);console.log(myArr[0]); // Output: Ford
Parsing with Dates
Manual Conversion
The JSON.parse() method converts the JSON string into a JavaScript object. Then, the birth property, which is a string, is manually converted to a Date object using a new Date().
const text = '{"name":"Sam", "birth":"2000-01-19", "city":"Hyderabad"}';const obj = JSON.parse(text);obj.birth = new Date(obj.birth);console.log(obj.birth); // Output: Date object
Handling Functions
Handling functions in JSON involves parsing function definitions stored as strings and converting them back to executable functions using techniques like eval()
const text = '{"name":"Sam", "age":"function () {return 24;}", "city":"Hyderabad"}'; const obj = JSON.parse(text); obj.age = eval("(" + obj.age + ")"); console.log(obj.age()); // Output: 24
Validation
Below are the validation methods in JSON
Method | Description | Example Code |
---|---|---|
JSON.parse | Check if a string is valid JSON. Throws error if invalid. | try { JSON.parse(jsonStr); console.log("Valid JSON"); } catch (e) { console.log("Invalid JSON"); } |
ajv.validate | Validates JSON data against a schema using Ajv. | const Ajv = require("ajv"); const ajv = new Ajv(); const valid = ajv.validate(schema, data); |
isJSON (Custom) | Custom function to validate JSON without exceptions. | const isJSON = (str) => { try { JSON.parse(str); return true; } catch { return false; } }; |
Performance Optimization
The following are the performance optimization strategies in JSON for JavaScript
Strategy | Action | Syntax |
---|---|---|
Minimizing JSON Size |
|
const compactJson = JSON.stringify(data); Example: {"name":"Ram","age":22} |
Parsing JSON Efficiently |
|
const parsedData = JSON.parse(jsonString); Example: JSON.parse('{"name":"Ram"}') |
Caching JSON Data |
|
localStorage.setItem('jsonData', JSON.stringify(data)); Example: localStorage.getItem('jsonData') |