Joshna Gunturu
Joshna Gunturu

Reputation: 161

How to store JSON in a variable

How to store data as JSON like a database, so that when a user registers the information should be stored in a variable?

Example:

My HTML form consists of input text fields firstname, lastname. Clicking the register button of the form should store the values of firstname and lastname in a variables.

How can I do this:

 var txt = '{"employees":[' +
   '{"firstName":"John","lastName":"Doe" },' +
    '{"firstName":"Anna","lastName":"Smith" },' +
     '{"firstName":"Peter","lastName":"Jones" }]}';

Upvotes: 2

Views: 24394

Answers (4)

Carsten Massmann
Carsten Massmann

Reputation: 28196

You can add data to the actual data structure by appending it to the employees array like

dataobj.employees.push({"firstName":$('input[name=firstn]').val(),
                        "lastName":$('input[name=lastn]').val() });

Of course, this requires that the JSON was parsed into the dataobj in the first place. It must be serialized again if you want to send it by GET. But it can be POSTed directly as a data object!

You can of course also start with an empty array, initializing dataobj like

var dataobj={ employee: [] };

before the above uptdating command comes into action.

A very late edit ...

Just in case there should be multiple firstname / lastname input fields, then the following will do a "much better" job (as it will have a look at all fields and collect only those where at least one of the names is set):

var dataobj={employees:[]};
function shw(){
  $('#out').text(JSON.stringify(dataobj).replace(/{/g,'\n{'));}
$(function(){
  $('#clr').click(function(){dataobj.employees=[];shw()});
  $('#go').click(function(){
   var ln=$('input[name=lastn]').toArray();     // ln: JS-Array of DOM elements
   $('input[name=firstn]').each(function(i,fn){ // for each fn DOM-element ...
    var f=fn.value,l=ln[i].value;               // get values as strings
    if (f+l>'') dataobj.employees.push({firstName:f,lastName:l}); // push name object
   });shw();})
  shw();
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="text" name="firstn" value="John"><input type="text" name="lastn" value="Doe"><br>
<input type="text" name="firstn" value="Anna"><input type="text" name="lastn" value="Smith"><br>
<input type="text" name="firstn" value="Peter"><input type="text" name="lastn" value="Jones">
<input type="button" id="go" value="append names">
<input type="button" id="clr" value="clear">
<pre id="out"></pre>

Upvotes: 1

Patt Mehta
Patt Mehta

Reputation: 4194

You can use the push method of array to push JSON data. This is shown here - appending-to-a-json-object. Before the data needs to be submitted (say to process.php), stringify it.

Upvotes: 0

Paul S.
Paul S.

Reputation: 66304

Sounds like you want to go from values in HTML to a JSON string. Assuming <form> looks like this

<form>
    <input type="text" name="nm1[]"/><input type="text" name="nm2[]"/>
    <input type="text" name="nm1[]"/><input type="text" name="nm2[]"/>
</form>

You can use getElementsByName twice, build an Object and JSON.stringify it

var nm1 = document.getElementsByName('nm1[]'),
    nm2 = document.getElementsByName('nm2[]'),
    i, o = {
        employees: []
    };
for (i = 0; i < nm1.length; ++i) {
    if (nm1[i].value && nm2[i].value)
        o.employees.push({
            firstName: nm1[i].value,
            lastName: nm2[i].value
        });
}
JSON.stringify(o);

DEMO (open console)

Upvotes: 2

rainer zufall
rainer zufall

Reputation: 100

Easily use Jquery

var jsonArray;
jsonArray.push($("#firstname").val();
jsonArray.push($("#lastname").val();
var myJsonString = JSON.stringify(jsonArray);

Upvotes: 0

Related Questions