使用Javascript在Postman中进行Json Body Array验证

时间:2017-08-03 14:19:00

标签: javascript json postman

我的Json回应如下....

{
  "errors": [
    {
      "status": "XXXX",
      "source": ["pointer","value"],
      "detail": "ZZZZZZZZZZZZZZ."
    },
    {
      "status": "XXXX",
      "source": ["pointer","value"],
      "detail": "ZZZZZZZZZZZZZZZ."
    },
    {
      "status": "XXXX",
      "source": ["pointer"],
      "title": " ZZZZZZZZZZZZZZZZ"
     }
  ]
}

我必须检查天气来源所有字段中都有指针和值。 我尝试了下面的一些事情。

responseJson = JSON.parse(responseBody);
var list = responseBody.length;

tests["Expected fields"] = list === undefined || errors[0].source=== ["pointer","value"];

有人可以帮忙吗?

1 个答案:

答案 0 :(得分:0)

你需要这样的东西:



var dataHaveIt = {
  "errors": [{
      "status": "XXXX",
      "source": ["pointer", "value"],
      "detail": "ZZZZZZZZZZZZZZ."
    },
    {
      "status": "XXXX",
      "source": ["pointer", "value"],
      "detail": "ZZZZZZZZZZZZZZZ."
    }
  ]
};

var dataDontHaveIt = {
  "errors": [{
      "status": "XXXX",
      "source": ["pointer", "value"],
      "detail": "ZZZZZZZZZZZZZZ."
    },
    {
      "status": "XXXX",
      "source": ["pointer", "value"],
      "detail": "ZZZZZZZZZZZZZZZ."
    },
    {
      "status": "XXXX",
      "source": ["pointer"],
      "title": " ZZZZZZZZZZZZZZZZ"
    }
  ]
};

var allHaveIt = false;
allHaveIt = dataHaveIt.errors.reduce(function(result, element) {
  return result && element.source.includes("pointer") && element.source.includes("value")
}, true);

console.log(allHaveIt);

allHaveIt = dataDontHaveIt.errors.reduce(function(result, element) {
  return result && element.source.includes("pointer") && element.source.includes("value")
}, true);

console.log(allHaveIt)




实际工作在以下代码中完成:

allHaveIt = dataHaveIt.errors.reduce(function(result, element) {
  return result && element.source.includes("pointer") && element.source.includes("value")
}, true);

当作为最后一个参数true传递给reduce()方法时,我们假设所有值都存在,那么reduce()将遍历所有元素,并且在includes()的帮助下我们可以检查source属性是否包含这些元素