JSON Server

JSON Server Interaction

The primary purpose of JSON is to safely transmit data between a web client and a server.

You can receive external data rapidly from a server, or securely send user data back to the server.


Receiving Data

If you request data from an external server or API, it arrives as a massive string of text.

To utilize this data inside your webpage, you immediately use JSON.parse().

Once parsed, you can bind the data to your HTML elements dynamically.


Sending Data

If you have data stored in a JavaScript object (like form inputs), you cannot send the object directly.

You must convert the JavaScript object into a text string using JSON.stringify().

This string is then attached to the body of an HTTP POST request and fired to the server!

Fetch API JSON Example:

// 1. Requesting JSON data from an external server
fetch('https://jsonplaceholder.typicode.com/users/1')
  .then(response => response.json()) // Automatically parses the JSON string!
  .then(data => {
    console.log("Received User:", data.name);
  });

// 2. Sending JSON data back to a server let myData = { name: "Alice", age: 25 };

fetch('https://example.com/api', { method: 'POST', headers: { 'Content-Type': 'application/json' }, // Instantly stringifying the object for transmission! body: JSON.stringify(myData) });


SEO and Fast Data Fetching

Modern Single Page Applications (SPAs) rely entirely on JSON server interactions to fetch data silently.

This eliminates massive full-page reloads, drastically increasing the speed of the user's experience.

Fast, responsive websites rank significantly higher on major search engines like Google!


Exercise 1 of 2

?

What must you do to a JavaScript object before sending it to a server via an HTTP POST request?

Exercise 2 of 2

?

When using the modern Fetch API, which method automatically parses the incoming JSON string?