使用数组值验证JSON响应

时间:2018-02-19 01:06:40

标签: json api

我有一个JSON响应,如下所示(在数组值中)。我想验证是否在响应中正确检索了Keys(属性)。我想比较一个预期值列表与响应值(只有第一组数组值) 例如:

"participants": [
    {
        "FirstName": "Kim",
        "LastName": "Hykes",
        "Street1": "ABC",
        "Street2": "ABCD",
        "City": "city1",
        "State": "NJ" 
    }

    {
        "FirstName": "John",
        "LastName": "David",
        "Street1": "XYZ",
        "Street2": "UXYZ",
        "City": "city2",
        "State": "NY" 
     } 
]

使用JSONparser,解析上面的JSON,结果将是:

participants[0].FirstName, participants[0].LastName, 
participants[0].Street1, participants[0].Street2, participants[0].City, 
participants[0].State, participants[1].FirstName, 
participants[1].LastName, 
participants[1].Street1, participants[1].Street2, participants[1].City, 
participants[1].State

它持续到50名参与者

我想看看是否从数据库中获取了所有必需的密钥,并且只想检查第一个数组字段,即仅在参与者[0]中。

任何人都可以帮我解决这个问题吗?

1 个答案:

答案 0 :(得分:0)

你的意思是这样的,要验证密钥是否在那里,并且顺序正确吗?

var response = {"participants": [
    {
        "FirstName": "Kim",
        "LastName": "Hykes",
        "Street1": "ABC",
        "Street2": "ABCD",
        "City": "city1",
        "State": "NJ" 
    },
    {
        "FirstName": "John",
        "LastName": "David",
        "Street1": "XYZ",
        "Street2": "UXYZ",
        "City": "city2",
        "State": "NY" 
     } 
]
}
var keysNeeded = ['FirstName', 'LastName', 'Street1', 'Street2', 'City', 'State']

var i = 0;

for (key in response.participants[0]) {
 if (key == keysNeeded[i]) {
 console.log('all is OK with key '+key)
 }
 i++;
}