Code360 powered by Coding Ninjas X Naukri.com. Code360 powered by Coding Ninjas X Naukri.com
Table of contents
1.
Introduction
2.
JSON.stringify()
2.1.
Parameter in JSON.stringify()
2.2.
Example of Converting Javascript Array to JSON.
2.3.
Using Function as Replacer in JSON.stringify()
2.4.
Using Array as Replacer in JSON.stringify()
2.5.
Using the Space Parameter of JSON.stringify()
3.
Javascript Array to JSON with indexes as Keys 
4.
Convert each item in a Javascript array to JSON
5.
toJSON() Behavior in Javascript
6.
Frequently Asked Questions
6.1.
What function does the toJSON property name serve?
6.2.
Why are paths crucial for cookie deletion?
6.3.
What are the JSON.stringify() function's exclusions?
7.
Conclusion
Last Updated: Mar 27, 2024
Easy

Javascript Array to JSON

Author Ayush Mishra
2 upvotes

Introduction

Javascript is a text-based programming language used on both the client and server sides to create interactive web pages. It adds interactive elements to websites that keep users interested, whereas HTML and CSS are languages that give web pages structure and style.

In this blog, we will discuss the conversion of Javascript Array to Json in deep detail. Let’s start going!

Javascript Array to Json

See, Javascript hasOwnProperty

JSON.stringify()

The method JSON.stringify() converts a JavaScript Array to JSON string, optionally replacing values if a replacer function or replacer array is specified or optionally including only the specified properties.

The syntax of JSON.stringify() is:-

🚀 JSON.stringify(value)

🚀 JSON.stringify(value, replacer)

🚀 JSON.stringify(value, replacer, space)

Parameter in JSON.stringify()

The parameter used in JSON.stringify are:-

🤖 value: It is the value to be converted into a string.

🤖 replacer: It is the optional parameter. The replacer can be a function that modifies the stringification process's behavior or an array that acts as a filter for the properties of the value object's value objects to be included in the JSON string.

🤖 space: It is also an optional parameter. A number or string that is used to add white space, such as indentation and line breaks, to the output JSON string to make it easier to read.

Example of Converting Javascript Array to JSON.

The below example converts the javascript array to JSON:-

JSON.stringify([1, 2, 3, 4, 5]); // Output is ‘[1,2,3,4,5]’

JSON.stringify([1, "true", true]); // Output is ‘[1,”true”,true]’

JSON.stringify({ x: 6}); // Output is ‘{x:6}’

Using Function as Replacer in JSON.stringify()

The below example is used to filter the Object using the replacer parameter of the JSON.stringify() as a function:-

function replacer(key, value) 
	{
  		// Filtering out properties
  		if (typeof value === "string")
  			{
    			return undefined;
  			}
 				return value;
	}

const func = {
  foundation: "Toyota",
  model: "square",
  week: 35,
  transport: "car",
  month: 12,
};
JSON.stringify(func, replacer);

 

Output

'{"week":35,"month":12}'

Using Array as Replacer in JSON.stringify()

The below example is used to filter the Object using the replacer parameter of the JSON.stringify() as an array:-

const func = {
  foundation: "Toyota",
  model: "square",
  week: 35,
  transport: "car",
  month: 12,
};

JSON.stringify(foo, ["week", "month"]);

 

Output

'{"week":35,"month":12}'

Using the Space Parameter of JSON.stringify()

The space parameter of the JSON.stringify()  is used to indent the output with the extra spaces.

console.log(JSON.stringify({ a: 2 }, null, " "));

 

Output

{
 "a": 2
}

 

Using a tab character simulates the appearance of pretty standard print:

console.log(JSON.stringify({ a: 1, b: 2 }, null, "\t"));

 

Output

{
	"a": 1,
	"b": 2
}
Get the tech career you deserve, faster!
Connect with our expert counsellors to understand how to hack your way to success
User rating 4.7/5
1:1 doubt support
95% placement record
Akash Pal
Senior Software Engineer
326% Hike After Job Bootcamp
Himanshu Gusain
Programmer Analyst
32 LPA After Job Bootcamp
After Job
Bootcamp

Javascript Array to JSON with indexes as Keys 

You might prefer an object whose keys are the array indexes if you don't want the direct string representation of a JSON array. Use the Object.assign method along with JSON.stringify to obtain a JSON object from an array of index keys.

const array = ["Infosys", "Wipro", "Mahindra"]
const jsonString = JSON.stringify(Object.assign({}, array))

 

Output

{
  "0": "Infosys",
  "1": "Wipro",
  "2": "Mahindra"
}

Convert each item in a Javascript array to JSON

In order to convert each item in a javascript array to JSON, the map() function should be used to get the result.

const arr = [1, 2, 3]

const json_Strings = arr.map(item => JSON.stringify(item))

toJSON() Behavior in Javascript

When an object's toJSON() method is defined, its serialization behavior can be overridden.

const ob = {
  data: "data",

  toJSON(key) 
  	{
    return key ? `Nested object under key '${key}'` : this;
  	},
};

JSON.stringify(ob);  // '{"data":"data"}'

JSON.stringify({ob}); // '{"obj":"Nested object under key 'ob' "}'

JSON.stringify([ob]); // '["Nested object under key '0'"]'

For better practice, implement it on an online javascript editor.

Frequently Asked Questions

What function does the toJSON property name serve?

The toJSON() method modifies the stringification process if the given Object has a property named toJSON with a function as its value. The value returned by the toJSON() method will be serialized rather than the original value.

Why are paths crucial for cookie deletion?

We should define the cookie path to ensure we delete the correct cookie. Also, note that some browsers won't let you delete a cookie if you don't specify the path.

What are the JSON.stringify() function's exclusions?

We are unable to use the JSON.stringify() method circularly. When converting a BigInt value, the function throws a TypeError.

Conclusion

Congratulations on finishing the blog! We have studied the conversion of  Javascript Array to JSON. We further looked at the JSON.stringify()  to convert the Javascript array to a string.

We sincerely hope that this blog has improved your understanding of the conversion of Javascript Array to JSON, and if you want to learn more, then you can check articles on:-

🤖 Introduction to JSON

🦾 JSON.stringify()

🔑 Javascript vs. Query

 

Recommended problems -

 

Please refer to our guided pathways on Code studio to learn more about DSACompetitive ProgrammingJavaScriptSystem Design, etc. Enroll in our courses, and use the accessible sample exams and questions as a guide. For placement preparations, look at the interview experiences and interview package.

Please do upvote our blogs if you find them helpful and informative!

Happy Learning!

Previous article
How to create Two Dimensional Array in JavaScript?
Next article
JS Strings
Live masterclass