Kermit
Kermit

Reputation: 34055

Preparing specific JSON structure with array

I'm trying to prepare a JSON with a certain structure to send over REST. Every 250 events, I want to send a JSON payload with those events. I'm trying to emulate this using the code below, but it is not returning anything.

var eventQueue = new Array();

for (j = 0; j < 251; j++) {
    var curr_timestamp = new Date().getTime();

    eventQueue.push({
        "client_ip" : "127.0.0.1",
        "timestamp" : curr_timestamp,
        "user_name" : "Robert"
    });

    if(j = 250) {
        var jString = JSON.stringify(eventQueue);
        var payload = '{"root":{"user_data":[' + jString + ']}}';
    }
}

The JSON payload structure I need to create looks like:

{  
   "root":{  
      "user_data":[  
         {  
            "client_ip":"127.0.0.1",
            "timestamp":"1723452955",
            "user_name":"Robert"
         },
         {  
            "client_ip":"127.0.0.1",
            "timestamp":"1723452956",
            "user_name":"Robert"
         },
         {  
            "client_ip":"127.0.0.1",
            "timestamp":"1723452957",
            "user_name":"Robert"
         },
         ...
      ]
   }
}

Should I be using join instead to prepare the structure or is there a better approach?

Upvotes: 0

Views: 54

Answers (4)

chouyangv3
chouyangv3

Reputation: 505

PHPglue is right. and eventQueue is an array, so JSON.stringify() will return string with spare brackets around it. you dont need to add additional []. otherwise it would be user_data: [[...]]

Upvotes: 0

StackSlave
StackSlave

Reputation: 10627

Your code should look like this:

var resObj = {root:{user_data:[]}};
for(var i=0; i<251; i++){;
  resObj.root.user_data.push({
    client_ip: '127.0.0.1',
    timestamp: new Date().getTime(),
    user_name: 'Robert'
  });
}
console.log(resObj);

Upvotes: 1

x-ray
x-ray

Reputation: 3329

var eventQueue = [];

for (var j = 0; j < 250; j++) {
    eventQueue.push({
        client_ip: "127.0.0.1",
        timestamp: new Date().getTime(),
        user_name: "Robert"
    });
}

var payload = JSON.stringify({
    root: {
        user_data: eventQueue
    }
});

Upvotes: -1

Mike
Mike

Reputation: 294

You are using j = 0 incorrectly. At the very least it should be j==0. But if you want this to happen every 250 events then you can use mod (%)

var eventQueue = new Array();

for (j = 0; j < 251; j++) {
    var curr_timestamp = new Date().getTime();

    eventQueue.push({
        "client_ip" : "127.0.0.1",
        "timestamp" : curr_timestamp,
        "user_name" : "Robert"
    });

    if(j % 250 == 0) {
        var jString = JSON.stringify(eventQueue);
        var payload = '{"root":{"user_data":[' + jString + ']}}';
    }}

Upvotes: 1

Related Questions