Main Tutorials

How to convert JavaScript Array to JSON

In JavaScript, you can use JSON.stringify to convert an array or values into a JSON formatted string.


var output = {}
output[0] = "a";
output[1] = "b";
output[2] = "c";

console.log( JSON.stringify(output) );

Output


{
	"0":"a",
	"1":"b",
	"2":"c"
}

1. jQuery Ajax Request

Often times, you need to convert the JavaScript values into JSON before AJAX POST request. For example :


$(document).ready(function () {

    $("#search-form").submit(function (event) {

        event.preventDefault();

		// array
        var search = {}
		search["username"] = $("#username").val();
		search["email"] = $("#email").val();

		$.ajax({
			type: "POST",
			contentType: "application/json",
			url: "/api/search",
			data: JSON.stringify(search), // convert array to JSON
			dataType: 'json',
			cache: false,
			timeout: 100000,
			success: function (data) {

				console.log("SUCCESS : ", data);

			},
			error: function (e) {

				console.log("ERROR : ", e);

			}
		});

    });

});

References

  1. MDN – JSON.stringify()

About Author

author image
Founder of Mkyong.com, love Java and open source stuff. Follow him on Twitter. If you like my tutorials, consider make a donation to these charities.

Comments

Subscribe
Notify of
3 Comments
Most Voted
Newest Oldest
Inline Feedbacks
View all comments
sagar
4 years ago

how can I convert an array to object where the array is [0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0] and the required data is {“1”: 0, “2”: 0, …}

JustAGrumpyGuy
4 years ago
Reply to  sagar

console.log(JSON.stringify(Object.assign({},output)));

Will give:

{“0″:0,”1″:0,”2″:0,”3″:0,”4″:0,”5″:0,”6″:0,”7″:0,”8″:0,”9″:0,”10″:0,”11″:0,”12″:0,”13″:0,”14″:0,”15″:0,”16″:0,”17″:0,”18″:0,”19″:0,”20″:0,”21″:0,”22″:0,”23″:0,”24″:0,”25″:0,”26″:0,”27″:0,”28″:0,”29″:0,”30”:0}

JustAGrumpyGuy
4 years ago
Reply to  sagar

console.log(JSON.stringify(Object.assign({},output)));