使用 jquery 使用每个输入值动态创建 JSON

我遇到了一个情况,我想通过 PHP 读取 JSON 格式的一些数据,但是我在理解如何构造 Javascript 对象来动态创建 JSON 格式方面遇到了一些问题。

我的设想如下:

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

到目前为止,我已经通过每个输入的 Javascript 代码抓取数据,但我无法理解如何处理从这里开始。

var taskArray = {};


$("input[class=email]").each(function() {
var id = $(this).attr("title");
var email = $(this).val();


//how to create JSON?


});

如果可能的话,我想得到以下输出。

[{title: QA, email: 'a@a.com'}, {title: PROD, email: 'b@b.com'},{title: DEV, email: 'c@c.com'}]

其中电子邮件是由输入字段值获取的。

399120 次浏览

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

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

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

I tried this:

// Sample JS object
var varobject = {
name: "Name",
Intern: "Test",
};


// Converting JS object to JSON string
JSON.stringify(varobject);