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 the Author

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

Comments

Leave a Reply

avatar