正在检索Json字符串的一部分

Retrieving part of a Json string

本文关键字:一部分 字符串 Json 检索      更新时间:2023-09-26

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

如何检索到期日期?

谢谢!

为了更容易查看:

{
  "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;
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;

前提是:

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;

这不是的最佳答案。到目前为止,最好的答案是解析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