问题描述
我有一个像这样的JS数组: var
I have a JS array like this: var
Vehicles = [[,],[,]];
Vehicles [0][0] = "SUV"
Vehicles [0][1] = "Chevy";
Vehicles [1][0] = "SEDAN";
Vehicles [1][1] = "Nissan";
我研究了如何将多维数组转换为json但是我我想知道是否可以用更简单的方式完成。如何将上面的数组转换为如下的json字符串:
I looked into how to convert a multidimensional array into json but I was wondering if it could be done in a more simple way. How do I convert above array into a json string like such:
{"Vehicles" :
[{"typeClass":"SUV" , "typeVehicle":"Chevy"},
{"typeClass":"SEDAN" , "typeVehicle":"Nissan"}
]
}
我读过我可以使用JSON.stringify(Vehicles)。但是阵列是循环数据结构,因此不起作用。我应该只构建字符串,然后将其解析为JSON对象吗? 例如
I read I can use JSON.stringify(Vehicles). But the array is a cyclic datasctructure so that will not work. Should I just built the string and then parse it into a JSON object? Such as
var Vehicles = "SUV,Chevy;SEDAN,Nissan";
var MyJSONObject = JSON.parse(Vehicles);
谢谢, Robert
Thanks, Robert
推荐答案
这将产生你指定的输出。 This will produce the output you've specified.
function Vehicle(class_t, type_t)
{
this.typeClass = class_t;
this.typeVehicle = type_t;
}
function test1()
{
var tmp=new Array();
tmp[0] = new Vehicle("SUV", "Chevy");
tmp[1] = new Vehicle("SEDAN", "Nissan");
myDataObject = new Object;
myDataObject.Vehicles = tmp;
objectJSON = JSON.stringify(myDataObject);
console.log(objectJSON);
}
如果您希望转换现有阵列,可以使用小功能进行转换。
If you wished to convert your existing array, you could do so with a small function.
function test2()
{
var Vehicles = new Array();
Vehicles[0] = new Array("SUV", "Chevy");
Vehicles[1] = new Array("SEDAN", "Nissan");
Vehicles[2] = new Array("COUPE", "Mazda");
Vehicles[3] = new Array("ESTATE", "Volvo");
var i, n = Vehicles.length;
var tmp = new Array();
for (i=0; i<n; i++)
{
tmp[i] = new Vehicle( Vehicles[i][0], Vehicles[i][1] );
}
var mObj = new Object;
mObj.Vehicles = tmp;
var objJSON = JSON.stringify(mObj);
console.log(objJSON);
}