Top JSON Interview Questions and Answers

author image Hirely
at 10 Jan, 2025

Question: What is the difference between JSON.parse() and JSON.stringify() in JavaScript?

Answer:

JSON.parse() and JSON.stringify() are two commonly used methods in JavaScript for working with JSON data. They serve opposite purposes:

1. JSON.parse()

  • Purpose: Converts a JSON string into a JavaScript object.
  • Use case: When you receive data as a JSON string (e.g., from an API, server, or local storage) and need to convert it into an object that you can work with in JavaScript.

Syntax:

JSON.parse(text[, reviver]);
  • text: A valid JSON string that you want to parse into a JavaScript object.
  • reviver (optional): A function that can transform the resulting object before it is returned.

Example:

const jsonString = '{"name": "John", "age": 30}';
const jsonObject = JSON.parse(jsonString);

console.log(jsonObject);  // Output: { name: "John", age: 30 }
console.log(jsonObject.name);  // Output: John

In this example, JSON.parse() converts the jsonString into a JavaScript object that you can access like any other object.


2. JSON.stringify()

  • Purpose: Converts a JavaScript object into a JSON string.
  • Use case: When you need to send a JavaScript object (e.g., from the client to the server, or to save it in local storage) as a string representation in JSON format.

Syntax:

JSON.stringify(value[, replacer[, space]]);
  • value: The JavaScript object or value you want to convert into a JSON string.
  • replacer (optional): A function or array used to control which values should be included in the resulting JSON string.
  • space (optional): A string or number used to insert whitespace into the output JSON string for readability (for pretty printing).

Example:

const jsonObject = { name: "John", age: 30 };
const jsonString = JSON.stringify(jsonObject);

console.log(jsonString);  // Output: '{"name":"John","age":30}'

In this example, JSON.stringify() converts the jsonObject into a JSON string.


Key Differences:

FeatureJSON.parse()JSON.stringify()
PurposeConverts a JSON string into a JavaScript object.Converts a JavaScript object into a JSON string.
InputA valid JSON string.A JavaScript object (or array) or other data type.
OutputA JavaScript object (or array).A JSON string.
Common Use CasesParsing JSON data received from an API or file.Sending data to a server or saving data to storage.
Can Handle ArraysYes, JSON arrays are converted to JavaScript arrays.Yes, JavaScript arrays are converted to JSON arrays.
Supports FunctionsFunctions are not supported in JSON format.Functions cannot be converted to JSON using stringify.
Pretty Print OptionNot applicable.The space argument can be used to format the output (for pretty printing).

Example of JSON.parse() and JSON.stringify() Together:

// JavaScript object
const person = {
    name: "Alice",
    age: 25,
    isStudent: false
};

// Convert JavaScript object to JSON string
const jsonString = JSON.stringify(person);
console.log(jsonString);  // Output: '{"name":"Alice","age":25,"isStudent":false}'

// Convert JSON string back to JavaScript object
const parsedObject = JSON.parse(jsonString);
console.log(parsedObject);  // Output: { name: "Alice", age: 25, isStudent: false }

In this example:

  1. JSON.stringify() converts the JavaScript object into a JSON string.
  2. JSON.parse() then converts that string back into a JavaScript object.

Summary:

  • JSON.parse() is used to convert JSON strings into JavaScript objects.
  • JSON.stringify() is used to convert JavaScript objects into JSON strings.

Question: How can you access values in a JSON object in JavaScript?

Answer:

In JavaScript, once a JSON string is parsed into a JavaScript object using JSON.parse(), you can access the values of that object using dot notation or bracket notation. Both methods allow you to retrieve the values associated with specific keys.

1. Dot Notation

  • Dot notation is the most common way to access properties of an object.
  • You simply use the object followed by a dot and the property name.

Example:

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

// Accessing values using dot notation
console.log(jsonObject.name);  // Output: John
console.log(jsonObject.age);   // Output: 30
console.log(jsonObject.city);  // Output: New York

2. Bracket Notation

  • Bracket notation is useful when the property name is stored in a variable or contains special characters (such as spaces or dashes).
  • You use square brackets ([]) with the property name as a string.

Example:

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

// Accessing values using bracket notation
console.log(jsonObject["name"]);  // Output: John
console.log(jsonObject["age"]);   // Output: 30
console.log(jsonObject["city"]);  // Output: New York

3. Accessing Nested JSON Objects

If the JSON object contains nested objects, you can access nested values by chaining dot notation or bracket notation.

Example:

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

// Accessing nested values
console.log(jsonObject.person.name);  // Output: John
console.log(jsonObject.person.age);   // Output: 30

Alternatively, you can use bracket notation for nested properties:

console.log(jsonObject["person"]["name"]);  // Output: John
console.log(jsonObject["person"]["age"]);   // Output: 30

4. Using a Variable to Access Properties (Bracket Notation)

If the property name is dynamic or stored in a variable, you should use bracket notation.

Example:

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

const property = "age";  // Property name stored in a variable
console.log(jsonObject[property]);  // Output: 30

5. Accessing Array Elements in JSON

If the JSON object contains arrays, you can access elements within those arrays by using index notation (similar to regular JavaScript arrays).

Example:

const jsonString = '{"names": ["John", "Alice", "Bob"]}';
const jsonObject = JSON.parse(jsonString);

// Accessing array elements
console.log(jsonObject.names[0]);  // Output: John
console.log(jsonObject.names[1]);  // Output: Alice
console.log(jsonObject.names[2]);  // Output: Bob

Summary of Access Methods:

  • Dot notation: Use object.property to access the value of a property.
  • Bracket notation: Use object["property"] to access the value, especially useful when property names are dynamic, contain spaces, or have special characters.
  • Nested properties: Chain dot or bracket notation to access values inside nested objects.
  • Arrays in JSON: Use array index array[index] to access elements in arrays.

Example of Full Usage:

const jsonString = '{"user": {"name": "John", "age": 30}, "address": {"city": "New York", "postalCode": "10001"}}';
const jsonObject = JSON.parse(jsonString);

// Using dot notation
console.log(jsonObject.user.name);         // Output: John
console.log(jsonObject.address.city);      // Output: New York

// Using bracket notation for dynamic access
const key = "postalCode";
console.log(jsonObject.address[key]);     // Output: 10001

// Accessing an array inside JSON
const jsonWithArray = '{"fruits": ["apple", "banana", "cherry"]}';
const jsonObjectWithArray = JSON.parse(jsonWithArray);
console.log(jsonObjectWithArray.fruits[1]); // Output: banana

This approach works for any valid JSON object once it has been parsed.

Read More

If you can’t get enough from this article, Aihirely has plenty more related information, such as JSON interview questions, JSON interview experiences, and details about various JSON job positions. Click here to check it out.

Related Posts

Trace Job opportunities

Hirely, your exclusive interview companion, empowers your competence and facilitates your interviews.

Get Started Now