gpt4 book ai didi

javascript - 如何比较 JSON 正文对象名称(Keys)本身?

转载 作者:行者123 更新时间:2023-11-30 14:02:41 25 4
gpt4 key购买 nike

我对 Postman 很陌生。我想比较 JSON 正文对象响应。

json_response = JSON.parse(responseBody);
x=json_response.counter
pm.expect(x).to.equal("400");

它给了我相应“计数器”的 400 值(或键“计数器”的“400”值)

但我想将“计数器”与“计数器”本身进行比较。 (例如,Counter、Counter 等)

{

"counter": 400,
"validInMinutes": 660,
"currentCounter": 322,

}

基本上,我想测试收到的所有 JSON key 是否与我要查找的相同! 有简单的方法吗?

最佳答案

postman pm.expect uses the Chai library for assertions (这链接到 pm.cookies 但出于某种原因,pm.expect 的条目位于该标题下)。使用 the Chai API您可以通过说expect(someObject).to.have.keys(expectedKeys) 来验证响应具有您期望的键并定义键应该是什么:

//for convenience - in Postman, these would be readily available. 
var pm = {
expect: chai.expect,
response: {
json: function() {
// the response you would get
return { "counter": 400, "validInMinutes": 660, "currentCounter": 322 };
}
}
};

/* --- test script begins --- */

var expectedKeys = ["counter", "validInMinutes", "currentCounter"];

pm.expect(pm.response.json()).to.have.keys(expectedKeys); // OK
<script src="https://cdnjs.cloudflare.com/ajax/libs/chai/4.2.0/chai.min.js"></script>

这里有一些例子说明这种期望是如何失败的:

var pm = { 
expect: chai.expect,
response: {
json: function() {
// "Counter" starts with capital C
return { "Counter": 400, "validInMinutes": 660, "currentCounter": 322 };
}
}
};

/* --- test script begins --- */

var expectedKeys = ["counter", "validInMinutes", "currentCounter"];

pm.expect(pm.response.json()).to.have.keys(expectedKeys); // fails
<script src="https://cdnjs.cloudflare.com/ajax/libs/chai/4.2.0/chai.min.js"></script>

var pm = { 
expect: chai.expect,
response: {
json: function() {
// "counter" is missing
return { "validInMinutes": 660, "currentCounter": 322 };
}
}
};

/* --- test script begins --- */

var expectedKeys = ["counter", "validInMinutes", "currentCounter"];

pm.expect(pm.response.json()).to.have.keys(expectedKeys); // fails
<script src="https://cdnjs.cloudflare.com/ajax/libs/chai/4.2.0/chai.min.js"></script>

var pm = { 
expect: chai.expect,
response: {
json: function() {
//same object you have...
return { "counter": 400, "validInMinutes": 660, "currentCounter": 322 };
}
}
};

/* --- test script begins --- */

//...but there is an extra expected key
var expectedKeys = ["counter", "validInMinutes", "currentCounter", "otherKey"];

pm.expect(pm.response.json()).to.have.keys(expectedKeys); // fails
<script src="https://cdnjs.cloudflare.com/ajax/libs/chai/4.2.0/chai.min.js"></script>

关于javascript - 如何比较 JSON 正文对象名称(Keys)本身?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56041283/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com