Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to add values to a JSON object?

I have created an array with:

var msg = new Array();

then, I have a function that add values to this array, this function is:

function add(time, user, text){
    var message = [time, user, text];
    if (msg.length >= 50)
        msg.shift();

    msg.push(message);        
}

As you can see, if the array has 50 or more elements I remove the first with .shift(). Then I add an array as element.

Ok, the code works perfectly, but now I have to loop the msg array to create a JSON obj.

The JSON object should has this format:

var obj = [
{'time' : time, 'user' : user, 'text' : text},
{'time' : time, 'user' : user, 'text' : text},
{'time' : time, 'user' : user, 'text' : text}
]

I mean...i have to loop msg array and then store all the values inside the JSON object. I do not know how to "concatenate" the element of the array inside json obj.

Could you help me?

Thank you very much in advance!

like image 318
Damiano Avatar asked Jun 11 '10 08:06

Damiano


People also ask

Can you add variables to JSON?

Open the "Add variable to JSON body" request and notice how we're using the pre-request script to change the value of the variable present in the body right before the request is being sent.

How do you add to a JSON object in Python?

Steps for Appending to a JSON File In Python, appending JSON to a file consists of the following steps: Read the JSON in Python dict or list object. Append the JSON to dict (or list ) object by modifying it. Write the updated dict (or list ) object into the original file.


1 Answers

I'll give you an example from your add function:

function add(time, user, text){
    // this line is all I changed
    var message = {'time' : time, 'user' : user, 'text' : text};

    if (msg.length >= 50)
        msg.shift();

    msg.push(message);        
}

As you can see the message variable is no longer an array but it's the Object you want it to be.

From this you should be able to work out how to create a new array and add the values you want to it.

like image 109
Luca Matteis Avatar answered Sep 22 '22 00:09

Luca Matteis