子字符串JSON键

Substringing JSON keys

本文关键字:JSON 字符串      更新时间:2023-09-26

我有一个表单,其中包含使用以下命名转换的输入:

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

因此,我正在使用这个脚本(在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);

不确定"注释"部分来自哪里。可能是您可以通过标记中的name属性来修复的问题。否则,你总是可以做这样的事情:

function renameKeys(obj) {
    var 
        result = {},
        key,
        check,
        noteReg = /^note'[([^']]+)']$/;
    for(key in obj) {
        result[(check = key.match(noteReg)) === null ? key : check[1]] = typeof obj[key] == 'object' && toString.call(obj[key]) == '[object Object]' ? renameKeys(obj[key]) : obj[key];
    }
    return result;
}

可用于使用所需的键创建对象。

renameKeys({"note[url]":"URL","note[title]":"TITLE"}); 
// { url: 'URL', title: 'TITLE' }
renameKeys({"note[url]":"URL","note[title]":"TITLE", anotherObj: { thingA: 1234, 'note[thingB]': 9492}});
// { url: 'URL', title: 'TITLE', anotherObj: { thingA: 1234, thingB: 9492 } }

不过,请注意,如果您有类似note[asdf]的密钥和asdf的密钥的东西,那么最后迭代的那个将覆盖另一个。