Creating a JSON dynamically with each input value using jquery Creating a JSON dynamically with each input value using jquery json json

Creating a JSON dynamically with each input value using jquery


Like this:

function createJSON() {    jsonObj = [];    $("input[class=email]").each(function() {        var id = $(this).attr("title");        var email = $(this).val();        item = {}        item ["title"] = id;        item ["email"] = email;        jsonObj.push(item);    });    console.log(jsonObj);}

Explanation

You are looking for an array of objects. So, you create a blank array. Create an object for each input by using 'title' and 'email' as keys. Then you add each of the objects to the array.

If you need a string, then do

jsonString = JSON.stringify(jsonObj);

Sample Output

[{"title":"QA","email":"a@b"},{"title":"PROD","email":"b@c"},{"title":"DEV","email":"c@d"}] 


I don't think you can turn JavaScript objects into JSON strings using only jQuery, assuming you need the JSON string as output.

Depending on the browsers you are targeting, you can use the JSON.stringify function to produce JSON strings.

See http://www.json.org/js.html for more information, there you can also find a JSON parser for older browsers that don't support the JSON object natively.

In your case:

var array = [];$("input[class=email]").each(function() {    array.push({        title: $(this).attr("title"),        email: $(this).val()    });});// then to get the JSON stringvar jsonString = JSON.stringify(array);


May be this will help, I'd prefer pure JS wherever possible, it improves the performance drastically as you won't have lots of JQuery function calls.

var obj = [];var elems = $("input[class=email]");for (i = 0; i < elems.length; i += 1) {    var id = this.getAttribute('title');    var email = this.value;    tmp = {        'title': id,        'email': email    };    obj.push(tmp);}