简体   繁体   English

JSON编码对象数组

[英]JSON encode array of objects

I have an array of objects like so: 我有一个像这样的对象数组:

[{}, {}, {}]

I need to pass this array via Socket.io. 我需要通过Socket.io传递此数组。 Socket.io converts the array into JSON and I keep getting the circular structure to JSON error. Socket.io将数组转换为JSON,但我不断将循环结构转换为JSON错误。

Heres my current code: 这是我当前的代码:

for (var i = 0; i < 5; i++) {
    num = randRange(0, cards[type].length);
    playerCards.push(cards[type][num]);
}
socket.emit('updateCards', playerCards);

Does anyone know a way around this? 有谁知道解决这个问题的方法吗?

Thanks 谢谢

You would see the same error if you tried to do the following: 如果尝试执行以下操作,则会看到相同的错误:

for (var i = 0; i < 5; i++) {

    num = randRange(0, cards[type].length);
    playerCards.push(cards[type][num]);
    JSON.stringify(cards[type][num]) 
}

//socket.emit('updateCards', playerCards);

The tag attribute is likely the culprit. 标签属性可能是罪魁祸首。 In order for the JSON serializer to work you cannot have any circular references in the object being serialized. 为了使JSON序列化程序正常工作,您在要序列化的对象中不能有任何循环引用。 One option would be to pull out the information needed from the tag object and create a custom object instead. 一种选择是从标记对象中提取所需的信息,然后创建一个自定义对象。

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

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