You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
// Converting between JSON strings and JavaScript objectsconstjsonString='{"name": "John", "age": 30}';constjsonObject=JSON.parse(jsonString);// String to objectconstbackToString=JSON.stringify(jsonObject,null,2);// Object to formatted string// Pretty printing JSON with indentationconstprettyJson=JSON.stringify({user: {name: "John",age: 30}},null,2);// The '2' adds 2 spaces for indentation// Handling special casestry{// Parse JSON safely with error handlingconstdata=JSON.parse(potentiallyInvalidJson);}catch(error){console.error('Invalid JSON:',error.message);}
Accessing Data
// Different ways to access JSON dataconstdata={user: {name: "John",address: {city: "New York",zip: "10001"},hobbies: ["reading","music"]}};// Direct property accessconstname=data.user.name;// "John"constcity=data.user.address.city;// "New York"constfirstHobby=data.user.hobbies[0];// "reading"// Optional chaining for safe accessconstcountry=data.user.address?.country;// undefined (no error)// Destructuring for multiple valuesconst{ name,address: {city: userCity}}=data.user;
Modifying Data
// Adding and updating JSON dataconstuser={name: "John",age: 30};// Adding new propertiesuser.email="john@example.com";// Add single propertyObject.assign(user,{// Add multiple propertiesphone: "123-456-7890",country: "USA"});// Updating nested valuesconstcompany={details: {employees: [{id: 1,name: "John"}]}};// Update nested propertycompany.details.employees[0].name="John Doe";// Create copy with modificationsconstupdatedUser={
...user,// Spread existing propertiesage: 31,// Override specific propertyverified: true// Add new property};
Array Operations
// Working with JSON arraysconstusers=[{id: 1,name: "John",active: true},{id: 2,name: "Jane",active: false},{id: 3,name: "Bob",active: true}];// Finding elementsconstjohn=users.find(user=>user.name==="John");constactiveUsers=users.filter(user=>user.active);// Transforming arraysconstuserNames=users.map(user=>user.name);// Extract namesconstusersByID=users.reduce((acc,user)=>{// Create lookup objectacc[user.id]=user;returnacc;},{});// Sorting arraysusers.sort((a,b)=>a.name.localeCompare(b.name));// Sort by name