Stack Overflow is a community of 4.7 million programmers, just like you, helping each other.

Join them; it only takes a minute:

Sign up
Join the Stack Overflow community to:
  1. Ask programming questions
  2. Answer and help your peers
  3. Get recognized for your expertise

I am attempting to JSON.stringify() the following key/value pair, where the value is an array of objects.

var string = JSON.stringify({onlineUsers : getUsersInRoom(users, room)});

This is incorrect and gives the following error:

var string = JSON.stringify({onlineUsers : getUsersInRoom(users, room)});

                ^

TypeError: Converting circular structure to JSON

This is the method:

function getUsersInRoom(users, room) {
    var json = [];
    for (var i = 0; i < users.length; i++) {
        if (users[i].room === room) {

            json.push(users[i]);
        }
    }
    return json;
}

Added users data structure:

[
 {
     id:1,
     username:"",
     room:"room 1",
     client: {
         sessionId:1,
         key:value
     }
 },
 {
     // etc
 }
]

Added function to add user to users array.

function addUser(client) {
    clients.push(client);
    var i = clients.indexOf(client);
    if (i > -1) {
        users.push({
            id : i,
            username : "",
            room : "",
            client : clients[i]
        });
    }
}

Added screen capture of JavaScript array containing an object as well as key/value pairs inside an object.

enter image description here

Added screen capture of the clients array containing WebSocket objects. enter image description here

How do I correctly "stringify" {key: arrayOfObjects[{key:value,key:{}},{},{}]}?

share|improve this question
    
Can you please add your Client data structure as well. There must be something in your array that contains a circular reference. – Shaun Sharples Jan 29 at 20:41
up vote 1 down vote accepted
var data = { };
data.onlineUsers = getUsersInRoom();

var string = JSON.stringify(data);

Would this work for you?

edit

I just noticed your error is circular type, your user or room object is probably creating a circular reference.

User > Room > User > Room etc...

share|improve this answer

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.