Creating a JSON dynamically with each input value using jquery

JavascriptJqueryHtmlJson

Javascript Problem Overview


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.

Javascript Solutions


Solution 1 - Javascript

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"}] 

Solution 2 - Javascript

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 string
var jsonString = JSON.stringify(array);

Solution 3 - Javascript

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);
}

Solution 4 - Javascript

same from above example - if you are just looking for json (not an array of object) just use

function getJsonDetails() {
      item = {}
      item ["token1"] = token1val;
      item ["token2"] = token1val;
      return item;
}
console.log(JSON.stringify(getJsonDetails()))

this output ll print as (a valid json)

{ 
   "token1":"samplevalue1",
   "token2":"samplevalue2"
}

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionBaconJuiceView Question on Stackoverflow
Solution 1 - JavascriptATOzTOAView Answer on Stackoverflow
Solution 2 - JavascriptChrisFView Answer on Stackoverflow
Solution 3 - JavascriptSalmanView Answer on Stackoverflow
Solution 4 - JavascriptPravin BansalView Answer on Stackoverflow