Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Creating a JSON dynamically with each input value using jquery

I got a situation where I would like to read some data off a JSON format through PHP, however I am having some issues understanding how I should construct the Javascript object to create the JSON format dynamically.

My scenario is as follows:

<input title="QA" type="text" class="email"> <input title="PROD" type="text" class="email"> <input title="DEV" type="text" class="email"> 

The Javascript code I have so far goes through each input grabs the data, I am however unable to understand how to process from here on.

var taskArray = {};  $("input[class=email]").each(function() {   var id = $(this).attr("title");   var email = $(this).val();    //how to create JSON?  }); 

I would like to get the following output if possible.

[{title: QA, email: '[email protected]'}, {title: PROD, email: '[email protected]'},{title: DEV, email: '[email protected]'}] 

Where the email is acquired by the input field value.

like image 595
BaconJuice Avatar asked Feb 21 '13 18:02

BaconJuice


People also ask

How to create JSON data dynamically in JavaScript?

To create JSON object dynamically via JavaScript, we can create the object we want. Then we call JSON. stringify to convert the object into a JSON string. let sitePersonnel = {}; let employees = []; sitePersonnel.

Can JSON be dynamic?

A dynamic JSON file will be created to store the array of JSON objects. Consider, we have a database named gfg, a table named userdata. Now, here is the PHP code to fetch data from database and store them into JSON file named gfgfuserdetails. json by converting them into an array of JSON objects.

What is JSON parse in jQuery?

This parseJSON() Method in jQuery takes a well-formed JSON string and returns the resulting JavaScript value. Syntax: jQuery.parseJSON( json ) Parameters: The parseXML() method accepts only one parameter that is mentioned above and described below: json: This parameter is the well-formed JSON string to be parsed.


1 Answers

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"}]  
like image 54
ATOzTOA Avatar answered Oct 02 '22 17:10

ATOzTOA