In this article, we will discuss the top 30 JSON interview questions and answers that are frequently asked by hiring managers. 

Top 30 JSON Interview Questions and Answers
Top 30 JSON Interview Questions and Answers

Introduction to JSON

JSON (JavaScript Object Notation) is a lightweight data-interchange format that is widely used for data storage and exchange in web applications.

As JSON continues to gain popularity in web development, it is important for developers to have a strong understanding of the format and its usage.

To help you prepare for JSON-related interviews, we have compiled a list of top 30 JSON interview questions and answers with detailed explanations and code snippets.

Whether you are an experienced developer or just starting your career in web development, these interview questions will help you gain a better understanding of JSON and prepare you for your next interview.

So, let’s dive in!

1. What is JSON, and what does it stand for?

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.

2. What are the advantages of using JSON over XML?

There are several advantages of using JSON over XML, including:

  • JSON is easier to read and write than XML
  • JSON has better support for complex data structures
  • JSON is faster to parse than XML
  • JSON is more compact than XML

3. What are the basic data types supported by JSON?

The basic data types supported by JSON are:

  • String
  • Number
  • Object
  • Array
  • Boolean
  • Null

4. How do you represent an object in JSON?

An object in JSON is represented as a collection of key-value pairs enclosed in curly braces. For example:

{
    "name": "John",
    "age": 30,
    "address": {
        "street": "123 Main St",
        "city": "Anytown",
        "state": "CA",
        "zip": "12345"
    }
}

5. How do you represent an array in JSON?

An array in JSON is represented as a list of values enclosed in square brackets. For example:

[1, 2, 3, 4, 5]

6. How do you represent a string in JSON?

A string in JSON is represented as a sequence of zero or more Unicode characters enclosed in double quotes. For example:

"Hello, world!"

7. How do you represent a number in JSON?

A number in JSON is represented as a sequence of digits with an optional decimal point and exponent. For example:

42
3.14
-273.15
1e10

8. How do you represent a boolean value in JSON?

A boolean value in JSON is represented as either true or false. For example:

true
false

9. How do you represent null in JSON?

Null in JSON is represented as the keyword null. For example:

null

10. How do you access data in a JSON object?

You can access data in a JSON object by using dot notation or bracket notation. For example:

let obj = {
    "name": "John",
    "age": 30,
    "address": {
        "street": "123 Main St",
        "city": "Anytown",
        "state": "CA",
        "zip": "12345"
    }
};

console.log(obj.name); // "John"
console.log(obj["age"]); // 30
console.log(obj.address.city); // "Anytown"

11. How do you access data in a JSON array?

You can access data in a JSON array by using index notation. For example:

let arr = [1, 2, 3, 4, 5];

console.log(arr[0]); // 1
console.log(arr[2]); // 3

12. How do you convert a JSON string to a JavaScript object?

You can convert a JSON string to a JavaScript object by using the JSON.parse() method. For example:

let jsonStr = '{"name": "John", "age": 30}';

let obj = JSON.parse(jsonStr);

console.log(obj.name); // "John"
console.log(obj.age); // 30

13. How do you convert a JavaScript object to a JSON string?

You can convert a JavaScript object to a JSON string by using the JSON .stringify() method.

See also  JavaScript Spread Operator Examples

For example:

let obj = {
    "name": "John",
    "age": 30
};

let jsonStr = JSON.stringify(obj);

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

14. What is JSONP, and how does it work?

JSONP (JSON with Padding) is a technique that allows for retrieving data from a different domain than the one the web page was served from.

It works by adding a callback function to the JSON data, which is then executed on the client-side. Here’s an example of how JSONP works:

function handleData(data) {
    console.log(data);
}

let script = document.createElement("script");
script.src = "https://example.com/data.json?callback=handleData";
document.head.appendChild(script);

In this example, the server returns the JSON data wrapped in a function call to handleData.

The script element is added to the DOM, triggering the request to the server.

When the response comes back, the callback function is executed with the JSON data as its argument.

15. What is JSON Schema, and how is it used?

JSON Schema is a vocabulary that allows you to annotate and validate JSON documents.

It provides a way to describe the structure of JSON data and the constraints that should be applied to it.

Here’s an example of a JSON Schema that describes a person object

{
    "$schema": "http://json-schema.org/draft-07/schema#",
    "type": "object",
    "properties": {
        "name": {
            "type": "string"
        },
        "age": {
            "type": "integer"
        },
        "address": {
            "type": "object",
            "properties": {
                "street": {
                    "type": "string"
                },
                "city": {
                    "type": "string"
                },
                "state": {
                    "type": "string",
                    "enum": ["CA", "NY", "TX"]
                },
                "zip": {
                    "type": "string",
                    "pattern": "^\\d{5}$"
                }
            },
            "required": ["street", "city", "state", "zip"]
        }
    },
    "required": ["name", "age", "address"]
}

This schema specifies that a person object must have a name, age, and address property, where the address property has a street, city, state, and zip property.

The state property is limited to the values “CA”, “NY”, or “TX”, and the zip property must be a string of five digits.

16. How do you validate a JSON document against a JSON Schema?

You can validate a JSON document against a JSON Schema by using a JSON Schema validator library, such as AJV.

Here’s an example of how to use AJV to validate a JSON document:

const Ajv = require('ajv');
const ajv = new Ajv(); // options can be passed, e.g. {allErrors: true}

const schema = {
    "type": "object",
    "properties": {
        "name": {"type": "string"},
        "age": {"type": "number", "minimum": 0}
    },
    "required": ["name", "age"]
};

const data = {
    "name": "John",
    "age": 30
};

const validate = ajv.compile(schema);
const valid = validate(data);

if (!valid) {
    console.log(validate.errors);
}

In this example, the schema and data are defined, and a validator function is created with ajv.compile(). The valid variable is set to the result of the validator function, and if it’s false, the errors are printed to the console.

17. What is JSON Web Token (JWT), and how does it work?

JSON Web Token (JWT) is a compact, URL-safe means of representing claims to be transferred between two parties.

It’s commonly used for authentication and authorization in web applications.

A JWT consists of three parts: a header, a payload, and a signature. Here’s an example of a JWT

eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJzdWIiOiIxMjM0NTY3ODkwIiwibmFtZSI6IkpvaG4gRG9lIiwiaWF0IjoxNTE2MjM5MDIyfQ.SflKxwRJSMeKKF2QT4fwpMeJf36POk6yJV_adQssw5c

The header and payload are base64-encoded JSON strings, and the signature is a combination of the header and payload, signed with a secret key.

18. How do you decode and verify a JWT?

You can decode a JWT by splitting it into its three parts and decoding the base64-encoded header and payload. Here’s an example:

const jwt = require('jsonwebtoken');

const token = 'eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJzdWIiOiIxMjM0NTY3ODkwIiwibmFtZSI6IkpvaG4gRG9lIiwiaWF0IjoxNTE2MjM5MDIyfQ.SflKxwRJSMeKKF2QT4fwpMeJf36POk6yJV_adQssw5c';
const secret = 'mysecretkey';

const decoded = jwt.decode(token, {complete: true});
console.log(decoded.header); // { alg: 'HS256', typ: 'JWT' }
console.log(decoded.payload); // { sub: '1234567890', name: 'John Doe', iat: 1516239022 }

In this example, the JWT is decoded with the jwt.decode() function, and the complete option is set to true to include the header.

See also  Top 10 Differences Between Client Side & Server Side Scripting

The decoded header and payload are printed to the console.

19. How do you encode a JSON object as a JWT?

You can encode a JSON object as a JWT using the jwt.sign() function. Here’s an example:

const jwt = require('jsonwebtoken');

const payload = {
    sub: '1234567890',
    name: 'John Doe',
    iat: 1516239022
};
const secret = 'mysecretkey';

const token = jwt.sign(payload, secret, {expiresIn: '1h'});
console.log(token);

In this example, the jwt.sign() function is used to encode the payload object as a JWT, using the secret key to sign it. The expiresIn option is set to '1h' to set an expiration time of one hour. The encoded JWT is printed to the console.

20. What is JSONP, and how does it work?

JSONP (JSON with Padding) is a technique for loading data from a different domain in a web page using JavaScript.

It allows the web page to bypass the same-origin policy, which prevents scripts from different domains from accessing each other’s data.

To use JSONP, the web page includes a script tag that loads a JavaScript file from the server hosting the data. The URL of the script includes a callback function name as a query parameter. When the server returns the data, it wraps it in a call to the callback function, like this:

callbackFunction({"name": "John Doe", "age": 30})

21. What are some advantages of using JSON over XML?

There are several advantages of using JSON over XML:

  • JSON is easier to read and write than XML. JSON uses a simpler syntax, with fewer characters and tags, making it easier to understand and modify.
  • JSON is faster to parse than XML. JSON parsers are typically faster than XML parsers, making it faster to read and write data.
  • JSON is more compact than XML. JSON uses less bandwidth and storage than XML, making it more efficient for transferring and storing data.
  • JSON is more compatible with JavaScript than XML. JSON can be easily converted to JavaScript objects and arrays, making it easier to work with in web applications.

22. What are some disadvantages of using JSON over XML?

There are also some disadvantages of using JSON over XML:

  • JSON does not have a schema or validation mechanism. XML has a built-in schema and validation mechanism, which can ensure the correctness of the data.
  • JSON does not support comments. XML allows comments to be added to the data, which can help document the data.
  • JSON does not have a standardized way of handling namespaces. XML has a standardized way of handling namespaces, which can help prevent naming conflicts.
  • JSON does not have a standard for encoding binary data. XML has a standard for encoding binary data using Base64, which can be useful for transmitting images and other binary data.

23. How can you parse a JSON string in JavaScript?

You can parse a JSON string in JavaScript using the JSON.parse() method. Here’s an example:

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

console.log(obj.name);
console.log(obj.age);

In this example, the JSON.parse() method is used to parse the jsonString variable into a JavaScript object.

The name and age properties of the object are then printed to the console.

24. How can you stringify a JavaScript object to a JSON string?

You can stringify a JavaScript object to a JSON string using the JSON.stringify() method.

Here’s an example

const obj = {name: 'John Doe', age: 30};
const jsonString = JSON.stringify(obj);

console.log(jsonString);

In this example, the JSON.stringify() method is used to convert the obj variable to a JSON string.

See also  Top 20 CSS Box Sizing Interview Questions and Answers

The resulting JSON string is printed to the console.

25. How can you pretty-print a JSON string in JavaScript?

You can pretty-print a JSON string in JavaScript by using the JSON.stringify() method with the space parameter.

Here’s an example:

const obj = {name: 'John Doe', age: 30};
const jsonString = JSON.stringify(obj, null, 2);

console.log(jsonString);

In this example, the JSON.stringify() method is used with the null parameter to indicate that no special behavior is needed, and the 2 parameter to specify that the output should be indented with two spaces per level.

The resulting pretty-printed JSON string is printed to the console.

26. How can you access nested properties in a JSON object?

You can access nested properties in a JSON object using the dot notation or the bracket notation. Here’s an example:

const obj = {
    name: 'John Doe',
    address: {
        street: '123 Main St',
        city: 'Anytown',
        state: 'CA',
        zip: '12345'
    }
};

console.log(obj.address.street);
console.log(obj['address']['city']);

In this example, the obj variable contains a nested object with an address property.

The address.street property is accessed using the dot notation, while the address['city'] property is accessed using the bracket notation.

27. How can you check if a JSON string is valid?

You can check if a JSON string is valid using the JSON.parse() method. If the JSON string is not valid, the method will throw a syntax error.

Here’s an example:

const jsonString = '{"name": "John Doe", "age": }';
try {
    const obj = JSON.parse(jsonString);
    console.log(obj);
} catch (err) {
    console.error(err);
}

In this example, the jsonString variable contains an invalid JSON string with a missing value for the age property.

The JSON.parse() method is used to parse the string into a JavaScript object. If the string is not valid, a syntax error will be thrown and printed to the console.

28. How can you handle errors when parsing JSON strings in JavaScript?

You can handle errors when parsing JSON strings in JavaScript using a try...catch block.

Here’s an example:

const jsonString = '{"name": "John Doe", "age": }';
try {
    const obj = JSON.parse(jsonString);
    console.log(obj);
} catch (err) {
    console.error(err);
}

In this example, the jsonString variable contains an invalid JSON string with a missing value for the age property. The try...catch block is used to catch the syntax error thrown by the JSON.parse() method and print it to the console.

29. How can you create a JSON object in JavaScript?

You can create a JSON object in JavaScript by defining a JavaScript object and using the JSON.stringify() method to convert it to a JSON string.

Here’s an example:

const obj = {name: 'John Doe', age: 30};
const jsonString = JSON.stringify(obj);

console.log(jsonString);

In this example, the obj variable contains a JavaScript object. The JSON.stringify() method is used to convert the object to a JSON string, which is then printed to the console.

30. How can you modify a JSON object in JavaScript?

You can modify a JSON object in JavaScript by parsing the JSON string into a JavaScript object, modifying the object, and then using the JSON.stringify() method to convert it back to a JSON string.

Here’s an example:

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

obj.age = 31;

const newJsonString = JSON.stringify(obj);

console.log(newJsonString);

In this example, the jsonString variable contains a JSON string.

The JSON.parse() method is used to parse the string into a JavaScript object, which is then modified by changing the age property to 31.

The modified object is then converted back to a JSON string using the JSON.stringify() method, which is printed to the console.