【问题标题】:How can i modify the json response i get to make it look like this before saving to local storage在保存到本地存储之前,如何修改我得到的 json 响应使其看起来像这样
【发布时间】:2013-12-01 04:33:06
【问题描述】:

我收到如下所示的 json 响应:

{
    "+143500000": {
        "inbox": "active",

            "Messages": [{
                "id": "sms001",
                "Sender": "Tom",
                "Text": "hello world"
        }, {
            "id": "sms002",
                "Sender": "Jones",
                "Text": "bye world"
        }]

    }
}

我想将此响应保存到本地存储,但它需要看起来像这样

{
    "+143500000": {
        "inbox": "active",

            "Messages": {
            "sms001": {
                "Sender": "Tom",
                "Text": "hello world"
        },

            "sms002": {
                "Sender": "Jones",
                "Text": "bye world"
        }}

    }
}

如何修改我得到的响应以使其看起来像那样。我是 javascript 的初学者。您的帮助将不胜感激。希望有一个 javascript 或 jquery 示例来执行此操作。

谢谢

【问题讨论】:

  • 您要保存的不是有效的 json。
  • 我可能在放样品时犯了一个错误。但我希望你明白我想做什么

标签: javascript jquery ajax json local-storage


【解决方案1】:
// if your value is in `a`, then:
for (k in a)
  if (a.hasOwnProperty(k)) {
    hash = {};
    a[k].Messages.forEach(function(m) {
      hash[m.id] = m;
      delete m.id;
    });
  a[k].Messages = hash;
}

【讨论】:

    【解决方案2】:

    逻辑应该很容易理解。请注意,您的起始 json 具有 Messages 作为数组,但您要求它具有命名属性,因此必须将其转换为对象。

    var data = {
      "+143500000": {
        "inbox": "active",
        "Messages": [
          {
            "id":"sms001",
            "Sender":"Tom",
            "Text": "hello world"
          },
          {
            "id":"sms002",
            "Sender":"Jones",
            "Text": "bye world"
          }
        ]
      }
    };
    
    var messages = {};
    for (var i=0; i<data["+143500000"].Messages.length; ++i) {
      var item = data["+143500000"].Messages[i];
      messages[item.id] = item;
      delete messages[item.id].id;
    }
    
    data["+143500000"].Messages = messages;
    console.log(data);
    
    data = JSON.stringify(data);
    console.log(data);
    
    localStorage.myJson = data;
    console.log(localStorage.myJson);
    
    var retrievedData = localStorage.myJson;
    console.log(retrievedData);
    

    Live demo here (click).

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2017-09-22
      • 1970-01-01
      • 1970-01-01
      • 2016-04-29
      • 1970-01-01
      • 2020-07-01
      • 1970-01-01
      相关资源
      最近更新 更多