【问题标题】:Split JSON object with square backet names into sub objects将带有方括号名称的 JSON 对象拆分为子对象
【发布时间】:2014-04-24 09:49:47
【问题描述】:

我们正在使用serializeObject 序列化表单,然后将其作为 JSON 编码字符串存储到本地存储中。当我们从 LocalStorage 中解码出来时,我们有名称为 flight[inbound][0][iso]flight[outbound][1][date] 等的键。这使得以后(在 JavaScript 中)很难正确循环,因为我们现在需要用存储的表单重新填充数据。

有没有办法将这些键名进一步解码为子对象?例如:

flight[outbound][0][datetime] = "Something";
flight[outbound][0][from]     = "Something";
flight[outbound][0][to]       = "Something";
flight[outbound][0][carrier]  = "Something";
flight[inbound][0][datetime]  = "Something";
flight[inbound][0][from]      = "Something";
flight[inbound][0][to]        = "Something";
flight[inbound][0][carrier]   = "Something";

应该变成:

flight = {
    outbound: {
        0: {
            datetime: "Something",
            from:     "Something",
            to:       "Something",
            carrier:  "Something",
        }
    },
    inbound: {
        0: {
            datetime: "Something else",
            from:     "Something else",
            to:       "Something else",
            carrier:  "Something else",
        }
    }
}

【问题讨论】:

  • serializeObject 的代码是什么?这在序列化到正确对象的步骤中应该是错误的。
  • 我撒谎了。这是gist.github.com/jbrooksuk/11248775
  • JSON 是什么样的?如果您将 JSON 转换为 JS 对象,您应该使用 JSON.Parse()
  • @James 所以这是一个 jQuery 插件?无论如何,您可以创建一个 jsfiddle 来重现您的问题吗?
  • 另见Javascript expando objects flight[outbound] 直接等于flight.outboundflight={outbound:{...}}

标签: javascript json forms


【解决方案1】:

事实证明,我们使用的 serializeObject 插件并没有做正确的工作。将其切换为 https://github.com/macek/jquery-serialize-object 为我们提供了我们所追求的。

【讨论】:

  • 您知道这是内置在 JavaScript 中的,不是吗?你根本不需要插件。此外,默认的 polyfill Json 序列化程序是 http://bestiejs.github.io/json3/。这是基于 JSON2 构建的,由发明 JSON 的人编写。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2016-06-02
  • 1970-01-01
  • 1970-01-01
  • 2013-08-18
  • 1970-01-01
  • 1970-01-01
  • 2020-12-21
相关资源
最近更新 更多