如何在保存到本地存储之前修改json响应,使其看起来像这样

时间:2013-11-18 05:33:44

标签: javascript jquery ajax json local-storage

我收到的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中的示例能够做到这一点。

由于

2 个答案:

答案 0 :(得分:1)

逻辑应该很容易遵循。请注意,您的起始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).

答案 1 :(得分:0)

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