javascript - 对 JSON 键进行子串化

标签 javascript jquery json

我有一个使用此命名约定输入的表单:

  <input class="xxlarge" name="note[url]" id="url" placeholder="URL">

所以,我正在使用 this script (在 StackOverflow 上找到)将表单数据序列化为 JSON。

$.fn.serializeObject = function()
{
var o = {};
var a = this.serializeArray();
$.each(a, function() {
    if (o[this.name] !== undefined) {
        if (!o[this.name].push) {
            o[this.name] = [o[this.name]];
        }
        o[this.name].push(this.value || '');
    } else {
        o[this.name] = this.value || '';
    }
});
return o;
};

在输出中我有这个:

  {"note[url]":"URL","note[title]":"TITLE"}

我想知道如何转换此脚本以获得如下输出:

  {"url":"URL","title":"TITLE"}

我使用相当标准的、记录的代码块来处理这个问题(使用函数,如上所述):

      $(function() {
      $('form').submit(function() {
        $('#result').html(JSON.stringify($('form').serializeObject()));
          $.post(
              "/api/create",
              JSON.stringify($('form').serializeObject()),
              function(responseText){
                  $("#result").html(responseText);
              },
              "html"
          );
          return false;
      });

提前致谢!

最佳答案

我建议将字符串解析为 JS 对象,更改 for 循环中的键,然后在完成后将其字符串化。就像这样:

// turn the string into a JS object
var data = JSON.parse('{"note[url]":"URL","note[title]":"TITLE"}');
var newData = {};
// step through each member
for(key in data) {
  // Regular expressions to find the brackets
  var newKeyStart = key.search(/note\[/) + 5;
  var newKeyEnd = key.search(/\]/);
  // pull out the desired part of the key
  var newKey = key.substr(newKeyStart,  newKeyEnd - newKeyStart);
  // insert into new data object
  newData[newKey] = data[key];
  }
// turn back into JSON again
var newJSON = JSON.stringify(newData);

关于javascript - 对 JSON 键进行子串化,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7576125/

相关文章:

javascript - 发送修改后的javascript

javascript - 如何通过 jQuery 中的 post 或 ajax 调用将参数传递给操作?

jquery - 循环遍历复选框并收集已选中复选框的名称 - JQuery

jquery - 改变位置的一个div内容

javascript - 带有 .bind() 的 jQuery .keyup() 不起作用

javascript - C# String.IsNullOrEmpty 等效的 Javascript

javascript - javascript 中的概要

php - 将特定数量的值从 php 返回到 Android

javascript - 按字母顺序对 JSON(按特定元素)排序

json - 过滤存储在 PostgreSQL 表中的 JSON 内部键