Json Objects in JavaScript
JSON Objects in JavaScript
What is a JSON Object?
A JSON Object is a collection of key/value pairs enclosed in curly braces
{}.Keys are strings (always in double quotes).
Values can be strings, numbers, booleans, null, arrays, or other objects.
JSON objects closely resemble JavaScript objects but are written as a string for data interchange.
JSON Object Example
{ "name": "Alice", "age": 28, "isStudent": false, "skills": ["JavaScript", "HTML", "CSS"], "address": { "city": "London", "postalCode": "E1 6AN" }}Working with JSON Objects in JavaScript
1. Parsing JSON string into a JavaScript object
const jsonString = `{ "name": "Alice", "age": 28, "isStudent": false, "skills": ["JavaScript", "HTML", "CSS"], "address": { "city": "London", "postalCode": "E1 6AN" }}`;const obj = JSON.parse(jsonString);console.log(obj.name); // Aliceconsole.log(obj.skills[0]); // JavaScriptconsole.log(obj.address.city); // London2. Creating a JavaScript object and converting it to JSON string
const person = { name: "Alice", age: 28, isStudent: false, skills: ["JavaScript", "HTML", "CSS"], address: { city: "London", postalCode: "E1 6AN" }};const jsonStr = JSON.stringify(person);console.log(jsonStr);Summary
| Operation | Method | Purpose |
|---|---|---|
| Convert JSON string ? Object | JSON.parse() | Parse JSON text into a JavaScript object |
| Convert Object ? JSON string | JSON.stringify() | Convert JavaScript object into JSON text |
If you'd like, I can show you how to manipulate JSON objects or fetch JSON data from APIs!