1

我还没有使用过 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": ""
        }, ]
    }
}

我怎样才能只检索到期日期?

谢谢!

4

4 回答 4

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;
于 2013-09-05T15:18:31.437 回答
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]);

演示

于 2013-09-05T15:35:21.527 回答
1

JSON 数据只是一个 javascript 对象。JSON 代表 Javascript 对象表示法。因此,您可以像在 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;
于 2013-09-05T15:17:19.117 回答
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;
于 2013-09-05T15:17:28.143 回答