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.

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()

上一篇: Spring REST API Validation
下一篇: Spring Boot Ajax example
 评论 ( What Do You Think )
名称
邮箱
网址
评论
验证
   
 

 


  • 微信公众号

  • 我的微信

站点声明:

1、一号门博客CMS,由Python, MySQL, Nginx, Wsgi 强力驱动

2、部分文章或者资源来源于互联网, 有时候很难判断是否侵权, 若有侵权, 请联系邮箱:summer@yihaomen.com, 同时欢迎大家注册用户,主动发布无版权争议的 文章/资源.

3、鄂ICP备14001754号-3, 鄂公网安备 42280202422812号