0

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?

asked Mar 22, 2017 at 1:07
1
  • 1
    j = 250 is assignment. Commented Mar 22, 2017 at 1:14

4 Answers 4

1

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 + ']}}';
 }}
answered Mar 22, 2017 at 1:21

Comments

1

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);
answered Mar 22, 2017 at 1:23

Comments

0

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: [[...]]

answered Mar 22, 2017 at 1:25

Comments

-1
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
 }
});
answered Mar 22, 2017 at 1:22

Comments

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.