Understanding JSON: The Essential Guide for Web Developers

Rashmi Mishra
0

 What is JSON?

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

 

Key Features of JSON

Text-Based Format: JSON is a text format that is completely language-independent, making it a great choice for data interchange.

 

Human-Readable: The structure of JSON is simple and easy to understand, which makes it accessible for developers and non-developers alike.

 

Data Structure: JSON represents data as key-value pairs, similar to how objects are structured in JavaScript.

 

Basic Structure of JSON

A JSON object is made up of: 

Objects: Enclosed in curly braces {} and consist of key-value pairs.

Arrays: Enclosed in square brackets [] and can contain multiple values.

Example of a JSON Object

Open In Editor

{

  "name": "John Doe",

  "age": 30,

  "isStudent": false,

  "courses": ["Math", "Science", "History"],

  "address": {

    "street": "123 Main St",

    "city": "Anytown",

    "zip": "12345"

  }

}

Breakdown of the Example

Key-Value Pairs: 

"name" is a key with the value "John Doe".

"age" is a key with the value 30.

"isStudent" is a key with the value false.

Array:

The key "courses" has an array as its value, containing three strings: "Math", "Science", and "History".

Nested Object: 

The key "address" contains another JSON object with its own key-value pairs.

Data Types in JSON

JSON supports the following data types: 

String: Text enclosed in double quotes (e.g., "Hello").

Number: Numeric values (e.g., 42, 3.14).

Boolean: true or false.

Array: An ordered list of values (e.g., ["apple", "banana", "cherry"]).

Object: A collection of key-value pairs (e.g., {"key": "value"}).

Null: Represents an empty value (e.g., null).

Common Uses of JSON

Web APIs: JSON is widely used in web APIs to send and receive data between clients and servers.

Configuration Files: Many applications use JSON for configuration settings due to its readability.

Data Storage: Some NoSQL databases (like MongoDB) use JSON-like formats to store data.

Conclusion

JSON is a versatile and widely-used format for data interchange. Its simplicity and readability make it a popular choice for developers working with web applications and APIs. Understanding JSON is essential for anyone looking to work with modern web technologies. 

### Advantages of JSON 

Lightweight: JSON is less verbose than XML, which means it requires less bandwidth and is faster to transmit.

Easy to Parse: Most programming languages have built-in support for parsing JSON, making it easy to work with.

Interoperability: JSON can be used across different programming languages, allowing for seamless data exchange between systems.

How to Use JSON

To use JSON in your applications, you typically follow these steps: 

Creating JSON: You can create JSON data manually or generate it programmatically using various libraries available in different programming languages. 

Parsing JSON: When you receive JSON data, you can parse it into a usable format in your programming language. For example, in JavaScript, you can use JSON.parse() to convert a JSON string into an object. 

Stringifying JSON: To send JSON data, you often need to convert your object back into a JSON string using JSON.stringify() in JavaScript. 

Example of Parsing and Stringifying JSON in JavaScript

Open In Editor

// JSON string

const jsonString = '{"name": "John Doe", "age": 30}';

 // Parsing JSON string to JavaScript object

const jsonObject = JSON.parse(jsonString);

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

 // Modifying the object

jsonObject.age += 1;

 // Stringifying the object back to JSON string

const updatedJsonString = JSON.stringify(jsonObject);

console.log(updatedJsonString); // Output: {"name":"John Doe","age":31}

Best Practices for Using JSON

Use Consistent Naming Conventions: Stick to a naming convention (like camelCase) for keys to maintain consistency.

Keep It Simple: Avoid deeply nested structures to enhance readability and ease of use.

Validate JSON: Use tools or libraries to validate your JSON data to ensure it is well-formed and adheres to the expected structure.

Conclusion

JSON is an essential format in modern web development, providing a simple and efficient way to handle data. By understanding its structure, advantages, and how to manipulate it, you can effectively integrate JSON into your applications and improve data interchange processes.

Assignments 

Assignment 1: Create a JSON Object

Task: 

Create a JSON object representing a book. The object should include the following properties: 

Title

Author

Year Published

Genres (an array of strings)

Is Available (a boolean)

Solution:

Open In Editor

{

  "title": "To Kill a Mockingbird",

  "author": "Harper Lee",

  "yearPublished": 1960,

  "genres": ["Fiction", "Drama", "Mystery"],

  "isAvailable": true

}

Explanation:

The JSON object contains key-value pairs for each property.

The genres property is an array that holds multiple genre strings.

The isAvailable property is a boolean indicating whether the book is available.

Assignment 2: Parse JSON Data

Task: Given the following JSON string, parse it into a JavaScript object and log the title and author to the console.

Open In Editor

{

  "title": "1984",

  "author": "George Orwell",

  "yearPublished": 1949

}

Solution: 

Open In Editor

const jsonString = '{"title": "1984", "author": "George Orwell", "yearPublished": 1949}';

const book = JSON.parse(jsonString);

console.log("Title:", book.title); // Output: Title: 1984

console.log("Author:", book.author); // Output: Author: George Orwell

Explanation:

The JSON.parse() method converts the JSON string into a JavaScript object.

We then access the title and author properties of the object and log them to the console.

Assignment 3: Modify a JSON Object

Task: Start with the following JSON object representing a movie. Add a new property called "rating" and set it to 8.5. Then convert the object back to a JSON string.

Open In Editor

{

  "title": "Inception",

  "director": "Christopher Nolan",

  "year": 2010,

  "genres": ["Action", "Sci-Fi"]

}

Solution:

Open In Editor

const movieJson = '{"title": "Inception", "director": "Christopher Nolan", "year": 2010, "genres": ["Action", "Sci-Fi"]}';

const movie = JSON.parse(movieJson);

 // Adding a new property

movie.rating = 8.5;

// Converting back to JSON string

const updatedMovieJson = JSON.stringify(movie);

console.log(updatedMovieJson);

Explanation: 

We parse the JSON string into a JavaScript object.

We add a new property rating to the object.

Finally, we use JSON.stringify() to convert the modified object back into a JSON string.

Assignment 4: Create an Array of JSON Objects

Task: Create an array of JSON objects representing three different students. Each student should have the following properties: name, age, and grades (an array of numbers). 

Solution: 

Open In Editor

[

  {

    "name": "Alice",

    "age": 20,

    "grades": [85, 90, 78]

  },

  {

    "name": "Bob",

    "age": 22,

    "grades": [88, 92, 80]

  },

  {

    "name": "Charlie",

    "age": 21,

    "grades": [90, 85, 95]

  }

]

Explanation:

 

The JSON array contains three objects, each representing a student.

Each student object has a name, age, and grades property, where grades is an array of numbers.

Assignment 5: Filter JSON Data

Task: Given the following array of student objects, filter out the students who have an average grade of 85 or higher.

 

json

 

Verify

 

Open In Editor

Edit

Copy code

[

  {

    "name": "Alice",

    "grades": [85, 90, 78]

  },

  {

    "name": "Bob",

    "grades": [88, 92, 80]

  },

  {

    "name": "Charlie",

    "grades": [90, 85, 95]

  }

]

Solution:

 

javascript

 

Verify

 

Open In Editor

Edit

Copy code

const studentsJson = '[{"name": "Alice", "grades": [85, 90, 78]}, {"name": "Bob", "grades": [88, 92, 80]}, {"name": "Charlie", "grades": [90, 85, 95]}]';

const students = JSON.parse(studentsJson);

 

// Function to calculate average

const calculateAverage = (grades ) => grades.reduce((a, b) => a + b, 0) / grades.length;

 

// Filtering students with average grade >= 85

const filteredStudents = students.filter(student => calculateAverage(student.grades) >= 85);

 

console.log(filteredStudents);

Explanation:

 

We first parse the JSON string into a JavaScript array of student objects.

The calculateAverage function computes the average of the grades for each student.

We then use the filter method to create a new array containing only those students whose average grade is 85 or higher. The result is logged to the console. ### Assignment 6: Nested JSON Object

Task: Create a JSON object representing a company. The object should include the following properties:

 

Name

Founded Year

Employees (an array of objects, each with name and position)

Headquarters (an object with city and country)

Solution:

 

json

 

Verify

 

Open In Editor

Edit

Copy code

{

  "name": "Tech Innovations",

  "foundedYear": 2010,

  "employees": [

    {

      "name": "Alice Smith",

      "position": "Software Engineer"

    },

    {

      "name": "Bob Johnson",

      "position": "Product Manager"

    }

  ],

  "headquarters": {

    "city": "San Francisco",

    "country": "USA"

  }

}

Explanation:

 

The JSON object represents a company with key-value pairs for its name and founded year.

The employees property is an array of objects, each containing the name and position of an employee.

The headquarters property is a nested object that includes the city and country.

Assignment 7: Convert JSON to a Table

Task: Given the following JSON array of products, convert it into an HTML table format.

 

json

 

Verify

 

Open In Editor

Edit

Copy code

[

  {

    "product": "Laptop",

    "price": 999.99,

    "inStock": true

  },

  {

    "product": "Smartphone",

    "price": 699.99,

    "inStock": false

  }

]

Solution:

 

javascript

 

Verify

 

Open In Editor

Edit

Copy code

const productsJson = '[{"product": "Laptop", "price": 999.99, "inStock": true}, {"product": "Smartphone", "price": 699.99, "inStock": false}]';

const products = JSON.parse(productsJson);

 

let htmlTable = '<table><tr><th>Product</th><th>Price</th><th>In Stock</th></tr>';

 

products.forEach(product => {

  htmlTable += `<tr>

    <td>${product.product}</td>

    <td>${product.price}</td>

    <td>${product.inStock}</td>

  </tr>`;

});

 

htmlTable += '</table>';

console.log(htmlTable);

Explanation:

 

We parse the JSON string into a JavaScript array of product objects.

We initialize an HTML table with headers and then loop through each product to create a table row with its details.

Finally, we log the complete HTML table string to the console.

Assignment 8: Validate JSON Structure

Task: Write a function that checks if a given JSON object representing a user has the required properties: username, email, and age.

 

Solution:

 

javascript

 

Verify

 

Open In Editor

Edit

Copy code

function validateUser (user) {

  const requiredProperties = ['username', 'email', 'age'];

  return requiredProperties.every(prop => prop in user);

}

 

const userJson = '{"username": "johndoe", "email": "john@example.com", "age": 25}';

const user = JSON.parse(userJson);

 

console.log(validateUser (user)); // Output: true

Explanation:

 

The validateUser  function checks if all required properties exist in the user object.

We parse the JSON string into a JavaScript object and then call the validation function, logging the result to the console.

Assignment 9: Merge Two JSON Objects

Task: Given two JSON objects representing user profiles, merge them into a single object. If there are overlapping properties, the values from the second object should take precedence.

 

Solution:

 

javascript

 

Verify

 

Open In Editor

Edit

Copy code

const user1Json = '{"username": "johndoe", "email": "john@example.com"}';

const user2Json = '{"email": "john.doe@example.com", "age": 25}';

 

const user1 = JSON.parse(user1Json);

const user2 = JSON.parse(user2Json);

 

// Merging the objects

const mergedUser  = { ...user1, ...user2 };

 

console.log(mergedUser );

Explanation:

 

We parse both JSON strings into JavaScript objects.

We use the spread operator to merge the two objects, allowing properties from user2 to overwrite those in user1 if they share the same key.

The merged object is logged to the console.

Assignment 10: Count Occurrences in JSON Array

Task: Given a JSON array of colors, count how many times each color appears.

 

json

 

Verify

 

Open In Editor

Edit

Copy code

["red", "blue", "green", "red", "blue", "blue"]

Solution:

 

javascript

 

Verify

 

Open In Editor

Edit

Copy code

const colorsJson = '["red", "blue", "green", "red", "blue", "blue"]';

const colors = JSON.parse(colorsJson);

 

const colorCount = {};

 

colors.forEach(color => {

  colorCount[color] = (colorCount[color] || 0) + 1;

});

 

console.log(colorCount);

Explanation:

 

We parse the JSON string into a JavaScript array of colors.

We initialize an empty object colorCount to store the occurrences of each color.

We loop through the array, updating the count for each color in the colorCount object.

Finally, we log the count of each color to the console, which will show how many times each color appears in the array. ### Assignment 11: Convert JSON to CSV Format

Task: Given the following JSON array of users, convert it into CSV format.

 

json

 

Verify

 

Open In Editor

Edit

Copy code

[

  {

    "name": "Alice",

    "age": 30,

    "city": "New York"

  },

  {

    "name": "Bob",

    "age": 25,

    "city": "Los Angeles"

  }

]

Solution:

 

javascript

 

Verify

 

Open In Editor

Edit

Copy code

const usersJson = '[{"name": "Alice", "age": 30, "city": "New York"}, {"name": "Bob", "age": 25, "city": "Los Angeles"}]';

const users = JSON.parse(usersJson);

 

let csv = 'Name,Age,City\n'; // CSV header

 

users.forEach(user => {

  csv += `${user.name},${user.age},${user.city}\n`;

});

 

console.log(csv);

Explanation:

 

We parse the JSON string into a JavaScript array of user objects.

We initialize a CSV string with headers.

We loop through each user and append their details to the CSV string.

Finally, we log the complete CSV string to the console.

Assignment 12: Deep Clone a JSON Object

Task: Write a function to deep clone a JSON object.

 

Solution:

 

javascript

 

Verify

 

Open In Editor

Edit

Copy code

function deepClone(obj) {

  return JSON.parse(JSON.stringify(obj));

}

 

const original = {

  name: "John",

  age: 30,

  address: {

    city: "New York",

    zip: "10001"

  }

};

 

const cloned = deepClone(original);

console.log(cloned);

Explanation:

 

The deepClone function uses JSON.stringify() to convert the object into a JSON string and then JSON.parse() to create a new object from that string.

This method effectively creates a deep copy of the original object, including nested properties.

Assignment 13: JSON Schema Validation

Task: Write a function that checks if a given JSON object representing a product has the required properties: name, price, and category.

 

Solution:

 

javascript

 

Verify

 

Open In Editor

Edit

Copy code

function validateProduct(product) {

  const requiredProperties = ['name', 'price', 'category'];

  return requiredProperties.every(prop => prop in product);

}

 

const productJson = '{"name": "Laptop", "price": 999.99, "category": "Electronics"}';

const product = JSON.parse(productJson);

 

console.log(validateProduct(product)); // Output: true

Explanation:

 

The validateProduct function checks if all required properties exist in the product object.

We parse the JSON string into a JavaScript object and then call the validation function, logging the result to the console.

Assignment 14: Flatten a Nested JSON Object

Task: Write a function to flatten a nested JSON object.

 

Solution:

 

javascript

 

Verify

 

Open In Editor

Edit

Copy code

function flattenObject(obj, prefix = '') {

  const flattened = {};

  for (const key in obj) {

    const newKey = prefix ? `${prefix}.${key}` : key;

    if (typeof obj[key] === 'object' && obj[key] !== null) {

      Object.assign(flattened, flattenObject(obj[key], newKey));

    } else {

      flattened[newKey] = obj[key];

    }

  }

  return flattened;

}

 

const nestedJson = {

  user: {

    name: "John",

    address: {

      city: "New York",

      zip: "10001"

    }

  }

};

 

const flattened = flattenObject(nestedJson);

console.log(flattened);

Explanation:

 

The flattenObject function recursively flattens the nested object by concatenating keys with a dot (.).

It checks if a property is an object and continues flattening until all properties are at the top level.

Assignment 15: Sort JSON Array by Property

Task: Given the following JSON array of products, sort them by price in ascending order.

 

json

 

Verify

 

Open In Editor

Edit

Copy code

[

  {

    "product": "Laptop",

    "price": 999.99

  },

  {

    "product": "Smartphone",

    "price": 699.99

  },

  {

    "product": "Tablet",

    "price": 299.99

  }

]

Solution:

 

javascript

 

Verify

 

Open In Editor

Edit

Copy code

const productsJson = '[{"product": "Laptop", "price": 999.99}, {"product": "Smartphone", "price": 699.99}, {"product": "Tablet", "price": 299.99}]';

const products = JSON.parse(productsJson);

 

products.sort((a, b) => a.price - b.price);

 

console.log(products);

Explanation: - We parse the JSON string into a JavaScript array of product objects.

 

We use the sort method to sort the array based on the price property in ascending order.

The sorted array is then logged to the console, showing the products arranged from the lowest to the highest price. ### Assignment 16: Group JSON Objects by Property

Task: Given the following JSON array of employees, group them by their department.

 

json

 

Verify

 

Open In Editor

Edit

Copy code

[

  {

    "name": "Alice",

    "department": "HR"

  },

  {

    "name": "Bob",

    "department": "Engineering"

  },

  {

    "name": "Charlie",

    "department": "HR"

  },

  {

    "name": "David",

    "department": "Engineering"

  }

]

Solution:

 

javascript

 

Verify

 

Open In Editor

Edit

Copy code

const employeesJson = '[{"name": "Alice", "department": "HR"}, {"name": "Bob", "department": "Engineering"}, {"name": "Charlie", "department": "HR"}, {"name": "David", "department": "Engineering"}]';

const employees = JSON.parse(employeesJson);

 

const groupedByDepartment = employees.reduce((acc, employee) => {

  const { department } = employee;

  if (!acc[department]) {

    acc[department] = [];

  }

  acc[department].push(employee.name);

  return acc;

}, {});

 

console.log(groupedByDepartment);

Explanation:

 

We parse the JSON string into a JavaScript array of employee objects.

We use the reduce method to create an object that groups employee names by their department.

The result is logged to the console, showing each department with its corresponding employees.

Assignment 17: Find Maximum Value in JSON Array

Task: Given the following JSON array of numbers, find the maximum value.

 

json

 

Verify

 

Open In Editor

Edit

Copy code

[10, 20, 5, 40, 30]

Solution:

 

javascript

 

Verify

 

Open In Editor

Edit

Copy code

const numbersJson = '[10, 20, 5, 40, 30]';

const numbers = JSON.parse(numbersJson);

 

const maxValue = Math.max(...numbers);

console.log(maxValue); // Output: 40

Explanation:

 

We parse the JSON string into a JavaScript array of numbers.

We use the Math.max() function along with the spread operator to find the maximum value in the array.

The maximum value is logged to the console.

Assignment 18: Create a JSON Object from User Input

Task: Create a JSON object representing a user based on user input for name, email, and age.

 

Solution:

 

javascript

 

Verify

 

Open In Editor

Edit

Copy code

const name = prompt("Enter your name:");

const email = prompt("Enter your email:");

const age = prompt("Enter your age:");

 

const user = {

  name: name,

  email: email,

  age: parseInt(age, 10)

};

 

const userJson = JSON.stringify(user);

console.log(userJson);

Explanation:

 

We use prompt to get user input for name, email, and age.

We create a user object with the input values and convert it to a JSON string using JSON.stringify().

The resulting JSON string is logged to the console.

Assignment 19: Remove a Property from a JSON Object

Task: Given the following JSON object representing a car, remove the "year" property.

 

json

 

Verify

 

Open In Editor

Edit

Copy code

{

  "make": "Toyota",

  "model": "Camry",

  "year": 2020

}

Solution:

 

javascript

 

Verify

 

Open In Editor

Edit

Copy code

const carJson = '{"make": "Toyota", "model": "Camry", "year": 2020}';

const car = JSON.parse(carJson);

 

// Removing the "year" property

delete car.year;

 

console.log(car);

Explanation:

 

We parse the JSON string into a JavaScript object.

We use the delete operator to remove the year property from the object.

The modified object is logged to the console, showing the car details without the year.

Assignment 20: Check for Duplicate Values in JSON Array

Task: Given the following JSON array of colors, check for duplicate values.

 

json

 

Verify

 

Open In Editor

Edit

Copy code

["red", "blue", "green", "red", "yellow"]

Solution:

 

javascript

 

Verify

 

Open In Editor

Edit

Copy code

const colorsJson = '["red", "blue", "green", "red", "yellow"]';

const colors = JSON.parse(colorsJson);

 

const hasDuplicates = new Set(colors).size !== colors.length;

console.log(hasDuplicates); // Output: true

Explanation:

 

We parse the JSON string into a JavaScript array of colors.

We use a Set to check for duplicates, as a Set only stores unique values.

We compare the size of the Set with the original array length to determine if there are duplicates, logging the result to the console.

Assignment 21: Convert JSON Array to Object with Unique Keys

** Task**: Given the following JSON array of users, convert it into an object where each user's name is the key and the value is the user's age.

 

json

 

Verify

 

Open In Editor

Edit

Copy code

[

  {

    "name": "Alice",

    "age": 30

  },

  {

    "name": "Bob",

    "age": 25

  },

  {

    "name": "Charlie",

    "age": 35

  }

]

Solution:

 

javascript

 

Verify

 

Open In Editor

Edit

Copy code

const usersJson = '[{"name": "Alice", "age": 30}, {"name": "Bob", "age": 25}, {"name": "Charlie", "age": 35}]';

const users = JSON.parse(usersJson);

 

const usersObject = users.reduce((acc, user) => {

  acc[user.name] = user.age;

  return acc;

}, {});

 

console.log(usersObject);

Explanation:

 

We parse the JSON string into a JavaScript array of user objects.

We use the reduce method to create an object where each key is the user's name and the value is their age.

The resulting object is logged to the console, showing the mapping of names to ages. ### Assignment 22: Merge Two JSON Arrays

Task: Given two JSON arrays of products, merge them into a single array without duplicates.

 

json

 

Verify

 

Open In Editor

Edit

Copy code

[

  {

    "product": "Laptop",

    "price": 999.99

  },

  {

    "product": "Smartphone",

    "price": 699.99

  }

]

json

 

Verify

 

Open In Editor

Edit

Copy code

[

  {

    "product": "Tablet",

    "price": 299.99

  },

  {

    "product": "Smartphone",

    "price": 699.99

  }

]

Solution:

 

javascript

 

Verify

 

Open In Editor

Edit

Copy code

const productsJson1 = '[{"product": "Laptop", "price": 999.99}, {"product": "Smartphone", "price": 699.99}]';

const productsJson2 = '[{"product": "Tablet", "price": 299.99}, {"product": "Smartphone", "price": 699.99}]';

 

const products1 = JSON.parse(productsJson1);

const products2 = JSON.parse(productsJson2);

 

const mergedProducts = [...products1, ...products2];

const uniqueProducts = Array.from(new Set(mergedProducts.map(p => p.product)))

  .map(product => mergedProducts.find(p => p.product === product));

 

console.log(uniqueProducts);

Explanation:

 

We parse both JSON strings into JavaScript arrays of product objects.

We merge the two arrays using the spread operator.

We create a unique array of products by using a Set to filter out duplicates based on the product name.

The final array of unique products is logged to the console.

Assignment 23: Count Properties in a JSON Object

Task: Given the following JSON object representing a person, count how many properties it has.

 

json

 

Verify

 

Open In Editor

Edit

Copy code

{

  "name": "John",

  "age": 30,

  "city": "New York",

  "isEmployed": true

}

Solution:

 

javascript

 

Verify

 

Open In Editor

Edit

Copy code

const personJson = '{"name": "John", "age": 30, "city": "New York", "isEmployed": true}';

const person = JSON.parse(personJson);

 

const propertyCount = Object.keys(person).length;

console.log(propertyCount); // Output: 4

Explanation:

 

We parse the JSON string into a JavaScript object.

We use Object.keys() to get an array of the object's keys and then check its length to count the properties.

The count of properties is logged to the console.

Assignment 24: Create a JSON Object from Form Data

Task: Create a JSON object representing a user based on form data (name, email, age).

 

Solution:

 

javascript

 

Verify

 

Open In Editor

Edit

Copy code

const formData = {

  name: "Jane Doe",

  email: "jane@example.com",

  age: 28

};

 

const userJson = JSON.stringify(formData);

console.log(userJson);

Explanation:

 

We create a JavaScript object representing the form data.

We convert the object to a JSON string using JSON.stringify().

The resulting JSON string is logged to the console.

Assignment 25: Find a Specific Object in a JSON Array

Task: Given the following JSON array of users, find the user with the name "Bob".

 

json

 

Verify

 

Open In Editor

Edit

Copy code

[

  {

    "name": "Alice",

    "age": 30

  },

  {

    "name": "Bob",

    "age": 25

  },

  {

    "name": "Charlie",

    "age": 35

  }

]

Solution:

 

javascript

 

Verify

 

Open In Editor

Edit

Copy code

const usersJson = '[{"name": "Alice", "age": 30}, {"name": "Bob", "age": 25}, {"name": "Charlie", "age": 35}]';

const users = JSON.parse(usersJson);

 

const userBob = users.find(user => user.name === "Bob");

console.log(userBob); // Output: { name: 'Bob', age: 25 }

Explanation:

 

We parse the JSON string into a JavaScript array of user objects.

We use the find method to locate the user object with the name "Bob".

The found user object is logged to the console.

Assignment 26: Convert JSON Object to Query String

Task: Given the following JSON object, convert it into a query string format.

 

json

 

Verify

 

Open In Editor

Edit

Copy code

{

  "name": "John Doe",

  "age": 30,

  "city": "New York"

}

Solution:

 

javascript

 

Verify

 

Open In Editor

Edit

Copy code

const personJson = '{"name": "John Doe", "age": 30, "city": "New York"}';

const person = JSON.parse(personJson);

 

const queryString = Object.keys(person)

  .map(key => `${encodeURIComponent(key)}=${encodeURIComponent(person[key])}`)

  .join('&');

 

console.log(queryString); // Output: name=John%20Doe&age=30&city=New%20York

Explanation:

 

We parse the JSON string into a JavaScript object.

We use Object.keys() to get the keys of the object and then map each key to a query string format using encodeURIComponent() to ensure proper encoding of special characters.

Finally, we join the array of query string parts with & to create the complete query string, which is logged to the console.

Tags

Post a Comment

0Comments

Post a Comment (0)