使用 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'}]

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

原文由 BaconJuice 发布,翻译遵循 CC BY-SA 4.0 许可协议

阅读 487
2 个回答

像这样:

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

解释

您正在寻找 an array of objects 。因此,您创建了一个空白数组。使用 ‘title’ 和 ‘email’ 作为键,为每个 input 创建一个对象。然后将每个对象添加到数组中。

如果你需要一个字符串,那么做

jsonString = JSON.stringify(jsonObj);

样本输出

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

原文由 ATOzTOA 发布,翻译遵循 CC BY-SA 3.0 许可协议

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

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

有关详细信息,请参阅 http://www.json.org/js.html ,您还可以在其中找到适用于本机不支持 JSON 对象的旧浏览器的 JSON 解析器。

在你的情况下:

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

原文由 ChrisF 发布,翻译遵循 CC BY-SA 3.0 许可协议

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题