How to Create JSON string in JavaScript

By | April 7, 2018

How to Create JSON string in JavaScript – The JSON Format Evaluates to JavaScript Objects. The JSON format is syntactically identical to the code for creating JavaScript objects. Because of this similarity, a JavaScript program can easily convert JSON data into native JavaScript objects.

Note:

* The JSON syntax is derived from JavaScript object notation syntax, but the JSON format is text only. Code for reading and generating JSON data can be written in any programming language.

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

Sometimes, you need to convert the JavaScript values into JSON before AJAX POST request. For JSON 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);
			}
		});

    });

});
For the next JSON example, you can learn How to Access JSON Object in JavaScript.

References

  1. MDN – JSON.stringify()

Leave a Reply

Your email address will not be published. Required fields are marked *