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

时间:2022-10-11 14:27:25

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.

我有一种情况,我想通过PHP读取JSON格式中的一些数据,但是我有一些问题,我需要理解如何构造Javascript对象来动态创建JSON格式。

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.

到目前为止,我所编写的Javascript代码遍历每个输入获取数据,但是我无法理解如何从这里开始处理。

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: 'a@a.com'}, {title: PROD, email: 'b@b.com'},{title: DEV, email: 'c@c.com'}]

Where the email is acquired by the input field value.

通过输入字段值获取电子邮件。

Any light shed on this situation will be greatly appreciated!

如有任何关于这种情况的消息,我们将非常感激!

4 个解决方案

#1


205  

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.

您正在寻找一个对象数组。创建一个空数组。使用“title”和“email”作为键,为每个输入创建一个对象。然后将每个对象添加到数组中。

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

#2


10  

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

假设需要JSON字符串作为输出,我认为仅使用jQuery不能将JavaScript对象转换成JSON字符串。

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

根据目标浏览器的不同,可以使用JSON。stringify函数生成JSON字符串。

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.

有关更多信息,请参见http://www.json.org/js.html,在那里您还可以为不支持JSON对象的旧浏览器找到JSON解析器。

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

#3


9  

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.

这可能会有帮助,我更喜欢纯粹的JS,它极大地提高了性能,因为您不会有很多JQuery函数调用。

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

#4


0  

you can also do

你也可以做

let str = '{" + yourKey + ":'+yourValue+'}'; str = JSON.parse(str);

让str = '{" + yourKey + ":'+yourValue+'}';str = JSON.parse(str);

#1


205  

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.

您正在寻找一个对象数组。创建一个空数组。使用“title”和“email”作为键,为每个输入创建一个对象。然后将每个对象添加到数组中。

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

#2


10  

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

假设需要JSON字符串作为输出,我认为仅使用jQuery不能将JavaScript对象转换成JSON字符串。

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

根据目标浏览器的不同,可以使用JSON。stringify函数生成JSON字符串。

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.

有关更多信息,请参见http://www.json.org/js.html,在那里您还可以为不支持JSON对象的旧浏览器找到JSON解析器。

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

#3


9  

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.

这可能会有帮助,我更喜欢纯粹的JS,它极大地提高了性能,因为您不会有很多JQuery函数调用。

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

#4


0  

you can also do

你也可以做

let str = '{" + yourKey + ":'+yourValue+'}'; str = JSON.parse(str);

让str = '{" + yourKey + ":'+yourValue+'}';str = JSON.parse(str);