➥ JS Tutorial
- JS HOME
- JS introduction
- JS Where to
- JS Output
- JS Statements
- JS Syntax
- JS Variables
- JS Operators
- JS Assignment
- JS Data Types
- JS Functions
- JS Objects
- JS Events
- JS Sting methods
- JS String Search
- JS Arrays Methods
- JS Arrays
- JS Sorting Arrays
- JS Array Iteration
- JS Math Object
- JS Comparison & Logical Operators
- JS if else and else if
- JS Switch Statement
- JS For Loop
- JS For In
- JS For Of
- JS While Loop
- JavaScript Break
- JS Sets
- JavaScript typeof
- JS Type Conversion
- JS Bitwise Operations
- JS JSON
- JS Best Practices
- JS Reserved Words
- JS Number Methods
➥ JS Objects
➥ JS Functions
➥ JS Classes
➥ JS HTML DOM
- JavaScript HTML DOM
- JS HTML DOM Document
- JS HTML DOM Elements
- Changing HTML
- JS Forms
- JS HTML DOM - CSS
- DOM Events
- HTML DOM Event Listener
➥ JS Browser BOM
➥ JS Web APIs
➥ JS AJAX
➥ JS JSON
Tutorial
JSON Object Literals
This is a JSON string:
'{"name":"John", "age":30, "car":null}'
Inside the JSON string there is a JSON object literal:
{"name":"John", "age":30, "car":null}
JSON object literals are surrounded by curly braces {}.
JSON object literals contains key/value pairs.
Keys and values are separated by a colon.
Keys must be strings, and values must be a valid JSON data type:
• a string
• a number
• an object
• an array
• a boolean
• null
Each key/value pair is separated by a comma.
JavaScript Objects
You can create a JavaScript object from a JSON object literal:
myObj = {"name":"John", "age":30, "car":null};
EXAMPLE ❯
Accessing Object Values
You can access object values by using dot (.) notation:
Example:
const myJSON = '{"name":"John", "age":30, "car":null}';
const myObj = JSON.parse(myJSON);
x = myObj.name;
You can also access object values by using bracket ([]) notation:
EXAMPLE ❯
Looping an Object
You can loop through object properties with a for-in loop:
Example:
const myJSON = '{"name":"John", "age":30, "car":null}';
const myObj = JSON.parse(myJSON);
let text = "";
for (const x in myObj) {
text += x + ", ";
}
In a for-in loop, use the bracket notation to access the property values: