start learning
Image 1
44766166366947

Javascript JSON responses

JSON (JavaScript Object Notation) is a lightweight data-interchange format. It's easy for humans to read and write, and easy for machines to parse and generate. JSON data is represented as key-value pairs, similar to JavaScript objects.

Example JSON data :

{
  "name": "John Doe",
  "age": 25,
  "city": "New York"
}

Parsing JSON

const jsonString = '{"name": "John Doe", "age": 25, "city": "New York"}';
const jsonObject = JSON.parse(jsonString);

console.log(jsonObject.name); // Output: John Doe

Stringifying JSON

const person = { "name": "John Doe", "age": 25, "city": "New York" };
const jsonString = JSON.stringify(person);

console.log(jsonString); // Output: {"name":"John Doe","age":25,"city":"New York"}

Handling JSON from API Responses

// Example using Fetch API
fetch('https://jsonplaceholder.typicode.com/todos/1')
  .then(response => response.json())
  .then(data => {
    console.log(data);
    // Now 'data' is a JavaScript object representing the JSON response
  })
  .catch(error => console.error('Error:', error));

Error Handling

Asynchronous JavaScript

Working with Nested Data

const nestedData = '{"user": {"name": "Alice", "address": {"city": "Wonderland"}}}';
const parsedData = JSON.parse(nestedData);

console.log(parsedData.user.name); // Output: Alice
console.log(parsedData.user.address.city); // Output: Wonderland

Modern JavaScript (Optional)

async function fetchData() {
  try {
    const response = await fetch('https://jsonplaceholder.typicode.com/todos/1');
    const data = await response.json();
    console.log(data);
  } catch (error) {
    console.error('Error:', error);
  }
}

fetchData();

By following these steps and examples, you should be well on your way to mastering working with JSON responses in JavaScript.

×