我有一个数组var cars = [2,3,..],其中包含几个整数。 我已经向数组中添加了一些值,但是现在我需要通过jQuery的.get方法将这个数组发送到页面。如何将其转换为JSON对象进行发送?


当前回答

最短的

从整数数组生成有效的json使用

let json = `[${cars}]`

对于更通用的数组,请使用JSON.stringify(cars)(对于带有循环引用的对象使用此方法)

Let cars = [1,2,3];cars.push(4、5、6); Let json = ' [${cars}] '; console.log (json); console.log (JSON.parse (json));// json验证

其他回答

最短的

从整数数组生成有效的json使用

let json = `[${cars}]`

对于更通用的数组,请使用JSON.stringify(cars)(对于带有循环引用的对象使用此方法)

Let cars = [1,2,3];cars.push(4、5、6); Let json = ' [${cars}] '; console.log (json); console.log (JSON.parse (json));// json验证

向后兼容的脚本: https://github.com/douglascrockford/JSON-js/blob/master/json2.js

和电话:

var myJsonString = JSON.stringify(yourArray);

注意:JSON对象现在是大多数现代web浏览器(IE 8及以上)的一部分。参见caniuse获取完整列表。感谢@Spudley在下面的评论

或者尝试将数组定义为对象。(var cars = {};)那么就不需要转换成json了。这在你的例子中可能不实用,但对我来说很管用。

我是这样做的:

如果我有:

var jsonArg1 = new Object();
    jsonArg1.name = 'calc this';
    jsonArg1.value = 3.1415;
var jsonArg2 = new Object();
    jsonArg2.name = 'calc this again';
    jsonArg2.value = 2.73;

var pluginArrayArg = new Array();
    pluginArrayArg.push(jsonArg1);
    pluginArrayArg.push(jsonArg2);

将pluginArrayArg(一个纯javascript数组)转换为JSON数组:

var jsonArray = JSON.parse(JSON.stringify(pluginArrayArg))

我决定使用json2库,我得到了一个关于“循环数据结构”的错误。

我通过告诉json2如何转换我的复杂对象来解决这个问题。它现在不仅可以工作,而且我只包括了我需要的字段。以下是我的做法:

OBJ.prototype.toJSON = function (key) {
       var returnObj = new Object();
       returnObj.devid = this.devid;
       returnObj.name = this.name;
       returnObj.speed = this.speed;
       returnObj.status = this.status;
       return returnObj;
   }