简体   繁体   English

Javascript的JSON.stringify不采用键索引(关联)数组吗?

[英]Javascript's JSON.stringify doesn't take key-indexed (associative) arrays?

In JavaScript, you can have objects, like this: 在JavaScript中,您可以具有如下对象:

var a = { foo: 12, bar: 34 };

Or arrays with key (named) indexes, like this: 或具有键(命名)索引的数组,如下所示:

var b = [];
b['foo'] = 56;
b['bar'] = 78;

They're somewhat similar, but obviously not the same. 它们有些相似,但显然不相同。

Now the strange thing is, JSON.stringify doesn't seem to take the array. 现在奇怪的是,JSON.stringify似乎没有采用数组。 No errors or anything, JSON.stringify(b) just results in []. 没有错误或任何东西,JSON.stringify(b)仅产生[]。

See this jsfiddle example . 请参阅此jsfiddle示例 Am I doing something wrong, or do I just misunderstand how arrays work? 我是在做错什么,还是只是误解了数组的工作原理?

Javascript doesn't support Associative arrays (Like PHP). Javascript不支持关联数组(如PHP)。

var b = []; Declaring explicitly an array, when you are trying to create an Object. 尝试创建对象时,显式声明一个数组。

Arrays in Javascript can only contain the Index approach of Arrays, while Objects are more of Associative arrays. Javascript中的数组只能包含数组的索引方法,而对象更多是关联数组。

If you change var b = []; 如果更改var b = []; to var b = {}; var b = {}; it will solve the problem. 它将解决问题。

var b = {} Declaring explicitly an Object. var b = {}显式声明一个对象。

Javascript arrays are objects. JavaScript数组是对象。 See https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Predefined_Core_Objects#Array_Object for details. 有关详细信息,请参见https://developer.mozilla.org/zh-CN/docs/Web/JavaScript/Guide/Predefined_Core_Objects#Array_Object

Note: if you supply a non-integer value to the array operator in the code above, a property will be created in the object representing the array, instead of an array element. 注意:如果您在上面的代码中为数组运算符提供了非整数值,则会在表示数组的对象中创建一个属性,而不是数组元素。

JSON supports only a subset of Javascript. JSON仅支持Javascript的子集。 See http://www.json.org/ for details. 有关详细信息,请参见http://www.json.org/

JSON is built on two structures: JSON建立在两种结构上:

  • A collection of name/value pairs. 名称/值对的集合。 In various languages, this is realized as an object, record, struct, dictionary, hash table, keyed list, or associative array. 在各种语言中,这被实现为对象,记录,结构,字典,哈希表,键列表或关联数组。
  • An ordered list of values. 值的有序列表。 In most languages, this is realized as an array, vector, list, or sequence. 在大多数语言中,这是通过数组,向量,列表或序列来实现的。

A Javascript array that has properties created in the underlying object does not fit into either of these structures because it has both a collection of name/value pairs and an ordered list of values, so there is no simple way to represent such an object directly in JSON. 具有在基础对象中创建的属性的Javascript数组不适合这两种结构,因为它既具有名称/值对的集合,又具有值的有序列表,因此,没有简单的方法可以直接在其中表示该对象JSON。

The JSON.stringify method is defined in the ECMAScript specification. JSON.stringify方法在ECMAScript规范中定义。 For example, see http://www.ecma-international.org/ecma-262/5.1/#sec-15.12.3 . 例如,请参阅http://www.ecma-international.org/ecma-262/5.1/#sec-15.12.3

While there are many details, the bit that is relevant here is how object values are stringified: 尽管有很多细节,但是这里相关的是如何对对象值进行字符串化:

If Type(value) is Object, and IsCallable(value) is false 如果Type(value)为Object,并且IsCallable(value)为false

  • If the [[Class]] internal property of value is "Array" then Return the result of calling the abstract operation JA with argument value. 如果value的[[Class]]内部属性为“ Array”,则返回使用参数value调用抽象操作JA的结果。
  • Else, return the result of calling the abstract operation JO with argument value. 否则,返回使用参数值调用抽象操作JO的结果。

Given your array, despite the addition of parameters to the underlying object, the result is of stringifying the ordered set of array elements, not the underlying object. 在给定数组的情况下,尽管向基础对象添加了参数,但结果是对数组元素而不是基础对象的有序集合进行了字符串化处理。

There is nothing wrong about adding parameters to an array object, but they are not part of the array and functions or methods that handle arrays might ignore them or deal with them arbitrarily. 向数组对象添加参数没有错,但是它们不是数组的一部分,处理数组的函数或方法可能会忽略它们或任意处理它们。 You have seen that JSON.stringify ignores the additional parameters. 您已经看到JSON.stringify忽略了其他参数。 Other functions might do otherwise - you will have to find out in each case. 其他功能可能会这样做-您将不得不在每种情况下找出答案。

While it is not wrong, it will probably be easier to understand if you do not add properties to array objects. 没错,但如果不向数组对象添加属性,可能会更容易理解。 If you want to add properties, start with a non-array object. 如果要添加属性,请从非数组对象开始。

Rather than: 而不是:

var b = [];
b['foo'] = 56;
b['bar'] = 78;

You might use: 您可以使用:

var b = {};
b['foo'] = 56;
b['bar'] = 78;

在此处输入图片说明

This snap is from IE explorer. 该快照来自IE资源管理器。 See the array is still blank. 看到数组仍然为空。

Actually the way of inserting the elements to the array is : 实际上,将元素插入数组的方式是:

1. Use push() 2. insert the elements in the array during declaration 1.使用push() 2.在声明期间将元素插入数组

If you want to stringify the array you have to have the data inside the array. 如果要对数组进行字符串化,则必须将数据保存在数组内部。

So, now you want to stringify the key value pairs so you have to pass the object as the argument of JSON.stringify() as follows: 因此,现在您想对键值对进行字符串化,因此必须将对象作为JSON.stringify()的参数传递,如下所示:

var test = {};           // Object
test['a'] = 'test';
test['b'] = [];          // Array
test['b'].push('item');
test['b'].push('item2');
test['b'].push('item3');
var json = JSON.stringify(test);
alert(json);

Solution to your problem now: 现在解决您的问题:

在此处输入图片说明

Note: Console of Google Chrome is giving different result, which is a bug in Google Chrome. 注意:谷歌浏览器的控制台给出了不同的结果,这是谷歌浏览器中的一个错误。

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

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