PDF

What is JSON?

JSON, which stands for JavaScript Object Notation, is a lightweight data interchange format that is easy for humans to read and write, and easy for machines to parse and generate. It is primarily used to transmit data between a server and a web application.

Step 1: JSON Structure

JSON is built on two structures:

  • Objects: Represented as key/value pairs, enclosed in curly braces {}. For example: { "name": "John", "age": 30 }.
  • Arrays: An ordered list of values, enclosed in square brackets []. For example: ["Apple", "Banana", "Cherry"].

Step 2: Basic Data Types in JSON

JSON supports several basic data types:

  • Strings: Text enclosed in quotes (e.g., "Hello World").
  • Numbers: Integers or floating-point numbers (e.g., 42, 3.14).
  • Booleans: True or false values.
  • Null: Represents an empty value.

Step 3: Creating a JSON Object

To create a JSON object, start with an opening curly brace, define your key/value pairs, and end with a closing curly brace. Here’s an example:

{
  "name": "Alice",
  "age": 25,
  "city": "New York"
}

Step 4: Using JSON in Applications

JSON is often used in web applications because it's easy to send data to and from a server. For example:

  • AJAX Calls: Use JSON as a format for fetching and sending data in web applications asynchronously.
  • APIs: Many RESTful APIs use JSON to structure data that is transferred between a client and a server.

Step 5: Parsing JSON

In JavaScript, you can convert a JSON string to a JavaScript object using JSON.parse() and convert an object back to a JSON string using JSON.stringify().

const jsonString = '{ "name": "Bob" }';
const jsonObj = JSON.parse(jsonString);
console.log(jsonObj.name); // Output: Bob

const newJsonString = JSON.stringify(jsonObj);
console.log(newJsonString); // Output: '{ 

Ask a followup question

Loading...