【问题标题】:I want to compare two json , one from response , one in DB我想比较两个 json ,一个来自响应,一个来自 DB
【发布时间】:2022-01-18 17:22:00
【问题描述】:
let body = response.body; // json after hitting the api using automation

 con.query("Select * FROM accounts WHERE name= '"+(Response.name+"'"), (err,rows,fields) => {            
      if(err) throw err;
      console.log('Fetch Query done successfully for accounts_master tables');

      var string=JSON.stringify(rows);
      console.log("STRING",string);
      var json = JSON.parse(string); //json i need to compare with above.
      console.log("NAMEEEE",json);

输出:-

{
    id: 11,
    name: 'manav',
    description: 'hellllllo',
    owner: 11,
}

我将在两个 json 中都得到这样的输出,而不是一一比较键值,我想将整个输出 json 与 DB 进行比较(我从 DB 中获取) 请告诉我同样的情况。

【问题讨论】:

  • 目标是什么?它必须相等还是你想看到差异?
  • 如果不相等,那么我想让测试用例失败,否则通过
  • 好吧,看看我的答案。

标签: sql node.js json testing automation


【解决方案1】:

要检查 2 个对象是否完全相等,您可以将它们作为字符串进行比较。 这样做:

// converts anyting to
function objToString(o) {
   // some safety..
   if(typeof o === 'string') {
       return o
   }
   return JSON.stringify(o)
}

// tests whetere 2 objects are equal
function isEqual(o1, o2) {
   return objToString(o1) === objToString(o2)
}

var obj1 = {
    key1: 'value1',
    key2: 'value2'
}

var obj2 = {
   key1: 'value1',
   key2: 'value2'
}

var obj3 = {
   key1: 'othervalue',
   key2: 'value2'
}

console.log(isEqual(obj1, obj2)) // => true
console.log(isEqual(obj1, obj3)) // => false
console.log(isEqual(obj2, obj3)) // => false

【讨论】:

    猜你喜欢
    • 2012-01-31
    • 2014-02-27
    • 1970-01-01
    • 1970-01-01
    • 2019-12-21
    • 2019-05-28
    • 1970-01-01
    • 1970-01-01
    • 2021-10-08
    相关资源
    最近更新 更多