简体   繁体   English

序列化一个javascript数组

[英]Serialize a javascript array

I have observed that in php you can encode an array and the resulting json does not carry the square brackets.However,in my javascript array, 我观察到在php中你可以编码一个数组,结果json不带方括号。但是,在我的javascript数组中,

var arrCars = new Array("Toyota", "Mercedes", "BMW");           
        var jsonStr = JSON.stringify(arrCars);
        alert(jsonStr);

i keep getting the square brackets.I have also noticed that if i use json stringfy, 我一直得到方括号。我也注意到如果我使用json stringfy,

var foo = {};  
foo.bar = "new property";  
foo.baz = 3;  

var JSONfoo = JSON.stringify(foo);

i get the json without the square just like i wanted.What must i do to my array to do away with the brackets?. 我得到的json没有正方形,就像我想要的那样。我必须对阵列做什么才能取消括号?

There's a difference between an array ( [] ) and an object ( {} ) in javascript. javascript中的数组( [] )和对象( {} )之间存在差异。 Your first example uses an array. 您的第一个示例使用数组。 Your second example uses an object. 您的第二个示例使用对象。 The main difference is that when you have an array ( [] ) the index can only be a zero based integer. 主要区别在于,当您有一个数组( [] )时,索引只能是一个基于零的整数。 Whereas an object can have property names that are strings. 而对象的属性名称可以是字符串。

The correct JSON for the array in your first example is ["Toyota","Mercedes","BMW"] , and the correct JSON for the object in your second example is either {"bar":"new property","baz":3} or {"baz":3,"bar":"new property"} . 第一个示例中阵列的正确JSON是["Toyota","Mercedes","BMW"] ,第二个示例中对象的正确JSON是{"bar":"new property","baz":3}{"baz":3,"bar":"new property"}

A JSON string contains either an object or an array, so it always has either curly brackets {} or square brackets [] . JSON字符串包含对象或数组,因此它始终具有大括号{}或方括号[]

If you get anything else, the result is not correct. 如果你得到其他任何东西,结果是不正确的。 If you expect anything else, your expectation is wrong. 如果您还有其他想法,那么您的期望是错误的。

If you want the curly brackets instead of the square brackets, you have to serialise an object, not an array. 如果你想要大括号而不是方括号,你必须序列化一个对象,而不是一个数组。

Not sure why you don't want brackets, since brackets are the normal way to make an array literal (as opposed to using the Array() function, as you do, which is way old-school) 不知道为什么你不想要括号,因为括号是制作数组文字的常规方法(而不是像你一样使用Array()函数,这是老派的方式)

If you want the JSON without the brackets, such as if you are building a bigger JSON string or something, you can use something like this: 如果你想要没有括号的JSON,比如你要构建一个更大的JSON字符串或什么东西,你可以使用这样的东西:

function jsonifyArrayWithoutBrackets(a) {
    var output = [];
    for (var i=0; i<a.length; i++)
        output.push(JSON.stringify(a[i]));
    return output.join(',');
}

Or, obviously, just trim the brackets off after using a single call to JSON.stringify(). 或者,显然,在使用一次调用JSON.stringify()之后,只需关闭括号。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM