检索Json字符串的一部分

时间:2013-09-05 15:13:02

标签: javascript jquery json

我还没有使用Json,所以这对我来说很新鲜。但是,我正在研究一个输出json字符串的系统,我必须从中检索一个在js脚本中使用的对象。

这是输出

{
    "SecureZoneSubscriptionList": {
        "EntityId": 51350993,
            "Subscriptions": [{
            "ZoneName": "FACCM    Membership",
                "ZoneId": "6460",
                "ExpiryDate": "9/5/2014 12:00:00 AM",
                "SellAccess": true,
                "CostPerPeriod": "0.1",
                "CycleType": ""
        }, ]
    }
}

如何检索到expiryDate?

谢谢!

4 个答案:

答案 0 :(得分:2)

为了更容易看到:

{
  "SecureZoneSubscriptionList": {
    "EntityId": 51350993,
    "Subscriptions": [
      {
        "ZoneName": "FACCM Membership",
        "ZoneId": "6460",
        "ExpiryDate": "9\/5\/2014 12:00:00 AM",
        "SellAccess": true,
        "CostPerPeriod": "0.1",
        "CycleType": ""
      }
    ]
  }
}

所以你会做以下事情:

var data= {"SecureZoneSubscriptionList": {"EntityId": 51350993,"Subscriptions": [{"ZoneName": "FACCM Membership","ZoneId": "6460","ExpiryDate": "9/5/2014 12:00:00 AM","SellAccess": true,"CostPerPeriod": "0.1","CycleType": ""}]}};
var expiryDate = data.SecureZoneSubscriptionList.Subscriptions[0].ExpiryDate;

如果您从服务器响应中将其作为字符串检索,则JSON.parse将获取该对象

var data = JSON.parse('{"SecureZoneSubscriptionList": {"EntityId": 51350993,"Subscriptions": [{"ZoneName": "FACCM Membership","ZoneId": "6460","ExpiryDate": "9/5/2014 12:00:00 AM","SellAccess": true,"CostPerPeriod": "0.1","CycleType": ""}]}}');
var expiryDate = data.SecureZoneSubscriptionList.Subscriptions[0].ExpiryDate;

答案 1 :(得分:1)

JSON数据只是一个javascript对象。 JSON代表Javascript Object Notation。因此,您可以像在JS中遍历对象属性一样获取数据:

var string = {"SecureZoneSubscriptionList": {"EntityId": 51350993,"Subscriptions": [{"ZoneName": "FACCM Membership","ZoneId": "6460","ExpiryDate": "9/5/2014 12:00:00 AM","SellAccess": true,"CostPerPeriod": "0.1","CycleType": ""},]}}

var expiryDate = string.SecureZoneSubscriptionList.Subscriptions[0].ExpiryDate;

答案 2 :(得分:1)

提供:

var fromServer = {"SecureZoneSubscriptionList": {"EntityId": 51350993,"Subscriptions": [{"ZoneName": "FACCM Membership","ZoneId": "6460","ExpiryDate": "9/5/2014 12:00:00 AM","SellAccess": true,"CostPerPeriod": "0.1","CycleType": ""},]}}

您将访问ExpiryDate:

var expDate = fromServer.SecureZoneSubscriptionList.Subscriptions[0].ExpiryDate;

答案 3 :(得分:1)

这是最佳答案。到目前为止,最好的答案是解析JSON并通过生成的对象访问您的值。话虽如此,JSON是一个字符串。当您需要字符串中的数据时,正则表达式始终是一个选项。

var myString = '{"SecureZoneSubscriptionList": { "EntityId": 51350993, "Subscriptions": [{ "ZoneName": "FACCM    Membership", "ZoneId": "6460", "ExpiryDate": "9/5/2014 12:00:00 AM",    "SellAccess": true,  "CostPerPeriod": "0.1",  "CycleType": ""        }, ] } }';
var matches = myString.match(/"ExpiryDate":\s?"([^"]*)"/);
alert(matches[1]);

DEMO