0

I have a JSON files which I want to compare the values and ensure both of the JSON is having the same values and return TRUE if there is any one of the value is not available then I need to return immediately FALSE.

The problem is now I'm having the two JSON files with Same Values but the row position is different.

JSON_1:

{
    "sqlQuery": "select type,subtype from wetrade_p2 where parent_id='69341269'",
    "message": "2 rows selected",
    "row": [
        {
            "column": [
                {
                    "value": "W",
                    "name": "TYPE"
                },
                {
                    "value": "P",
                    "name": "STATUS"
                },
                {
                    "value": "0",
                    "name": "SUBTYPE"
                },
                {
                    "value": "USD",
                    "name": "CURRENCY"
                }
            ]
        },
        {
            "column": [
                {
                    "value": "W",
                    "name": "TYPE"
                },
                {
                    "value": "S",
                    "name": "STATUS"
                },
                {
                    "value": "0",
                    "name": "SUBTYPE"
                },
                {
                    "value": "USD",
                    "name": "CURRENCY"
                }
            ]
  
        }
    ]
} 

JSON_2:

{
    "sqlQuery": "select type,subtype from wetrade_p2 where parent_id='69341269'",
    "message": "2 rows selected",
    "row": [
     {
            "column": [
                {
                    "value": "W",
                    "name": "TYPE"
                },
                {
                    "value": "S",
                    "name": "STATUS"
                },
                {
                    "value": "0",
                    "name": "SUBTYPE"
                },
                {
                    "value": "USD",
                    "name": "CURRENCY"
                }
            ]
  
        },
        {
            "column": [
                {
                    "value": "W",
                    "name": "TYPE"
                },
                {
                    "value": "P",
                    "name": "STATUS"
                },
                {
                    "value": "0",
                    "name": "SUBTYPE"
                },
                {
                    "value": "USD",
                    "name": "CURRENCY"
                }
            ]
        }
       
    ]
}

If you check the above JSON_1 and JSON_2 and both are having same values and but the ROW is mismatched/ JSON objects order is not remain same.Because of this the below code is return FALSE even thought the values are same:

Code:

compareActualAndExpectedResponse:function (jsonActual,jsonExpected)  {

                var jsonObject1 = JSON.parse(jsonActual);
                var jsonObject2 = JSON.parse(jsonExpected);
                var keys = Object.keys(jsonObject1);
                      for (var i = 0; i < keys.length; i++) {
                                 var key = keys[i];
                                      if (jsonObject1[key] != jsonObject2[key]) {
                                              console.log(key + " value changed from '" + jsonObject1[key] + "' to '" + jsonObject2[key] + "'");
                                              return false;
                                         }
                        }
                 return true;
}

UpdatedCode:

Utils.js:

var methods = {

            getuuid:function () {
                return 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, function (c) {
                    var r = Math.random() * 16 | 0, v = c == 'x' ? r : (r & 0x3 | 0x8);
                    return v.toString(16);
                  });
             },

             compareActualAndExpectedResponse:function (jsonActual, jsonExpected) {
                if (Object.prototype.toString.call(jsonActual) !==
                  Object.prototype.toString.call(jsonExpected)) {
                      console.log("false 1");
                  return false;
                }
              
                if (Array.isArray(jsonActual)) {
                  if (jsonActual.length !== jsonExpected.length) {
                      console.log("false 2")
                    return false;
                  }
              
                  let i = jsonActual.length;
              
                  while (i--) {
                    let j = jsonExpected.length;
                    let found = false;
              
                    while (!found && j--) {
                      if (compareActualAndExpectedResponse(jsonActual[i], jsonExpected[j])) found = true;
                    }
              
                    if (!found) {
                        console.log("false 3");
                      return false;
                    }
                  }
              console.log("true 1")
                  return true;
                }
              
                if (Object.prototype.toString.call(jsonActual) === '[object Object]') {
                  for (const key in jsonActual) {
                    if (Object.prototype.hasOwnProperty.call(jsonActual, key)) {
                      if (!Object.prototype.hasOwnProperty.call(jsonExpected, key)) {
                          console.log("false 4");
                          return false; 
                      }
              
                      if (!compareActualAndExpectedResponse(jsonActual[key], jsonExpected[key])) {
                        console.log("false 5")
                        return false;
                      }
                    }
                  }
                  for (const key in jsonExpected) {
                    if (Object.prototype.hasOwnProperty.call(jsonExpected, key) &&
                      !Object.prototype.hasOwnProperty.call(jsonActual, key)) {
                          console.log("false 6")
                      return false;
                    }
                  }
              console.log("true 2")
                  return true;
                }
              
                return jsonActual === jsonExpected;
              }
        };

module.exports = methods;

Client.JS:

var utils = require('./Utils');

 if(key.includes("entireJSONResponse"))
                  {
                    var data=fs.readFileSync(global.path+"/validationJSON/JSONResponseValidator/Bank.json",'utf8')
                    data=data.replace("{buyer}",transresult.get("buyeraccountnumber"));
                    const expected=JSON.stringify(transresult.get(key),null,4);
                    console.log(expected)
                    console.log(data);
                    var validationResult=utils .compareActualAndExpectedResponse(data,expected);
                    console.log(validationResult); //Still return false
                    console.log(utils.compareActualAndExpectedResponse(dataFinal,expected));
                    console.log("*************************************")
                  }
ArrchanaMohan
  • 2,314
  • 4
  • 36
  • 84
  • 1
    in your function even if the positions were the same, then the result would be `false`, because the objects are compared by reference `jsonObject1[key] != jsonObject2[key]` [Object comparison in JavaScript](https://stackoverflow.com/questions/1068834/object-comparison-in-javascript) – Nikita Madeev Aug 28 '20 at 08:17
  • I do not understand the question. The values **are not the same**. This 2 JSONs have different value for `STATUS` – Anton Aug 28 '20 at 10:26
  • Need to compare two json_1 and json_2. The order of json object will not remain same. But if you check the data inside json_1 and Json_2 will be same. Hope it helps. – ArrchanaMohan Aug 28 '20 at 10:42

1 Answers1

1

I solved a similar problem recently. Here's the code that I used, adapted to your usecase,

function compareActualAndExpectedResponse(jsonActual, jsonExpected) {
  if (Object.prototype.toString.call(jsonActual) !==
    Object.prototype.toString.call(jsonExpected)) {
    return false;
  }

  if (Array.isArray(jsonActual)) {
    if (jsonActual.length !== jsonExpected.length) {
      return false;
    }

    let i = jsonActual.length;

    while (i--) {
      let j = jsonExpected.length;
      let found = false;

      while (!found && j--) {
        if (compareActualAndExpectedResponse(jsonActual[i], jsonExpected[j])) found = true;
      }

      if (!found) {
        return false;
      }
    }

    return true;
  }

  if (Object.prototype.toString.call(jsonActual) === '[object Object]') {
    for (const key in jsonActual) {
      if (Object.prototype.hasOwnProperty.call(jsonActual, key)) {
        if (!Object.prototype.hasOwnProperty.call(jsonExpected, key)) {
            return false; 
        }

        if (!compareActualAndExpectedResponse(jsonActual[key], jsonExpected[key])) {
          return false;
        }
      }
    }


    for (const key in jsonExpected) {
      if (Object.prototype.hasOwnProperty.call(jsonExpected, key) &&
        !Object.prototype.hasOwnProperty.call(jsonActual, key)) {
        return false;
      }
    }

    return true;
  }

  return jsonActual === jsonExpected;
}


const JSON_1 = {
  sqlQuery: "select type,subtype from wetrade_p2 where parent_id='69341269'",
  message: '2 rows selected',
  row: [{
      column: [{
          value: 'W',
          name: 'TYPE',
        },
        {
          value: 'P',
          name: 'STATUS',
        },
        {
          value: '0',
          name: 'SUBTYPE',
        },
        {
          value: 'USD',
          name: 'CURRENCY',
        },
      ],
    },
    {
      column: [{
          value: 'W',
          name: 'TYPE',
        },
        {
          value: 'S',
          name: 'STATUS',
        },
        {
          value: '0',
          name: 'SUBTYPE',
        },
        {
          value: 'USD',
          name: 'CURRENCY',
        },
      ],

    },
  ],
};

const JSON_2 = {
  sqlQuery: "select type,subtype from wetrade_p2 where parent_id='69341269'",
  message: '2 rows selected',
  row: [{
      column: [{
          value: 'W',
          name: 'TYPE',
        },
        {
          value: 'S',
          name: 'STATUS',
        },
        {
          value: '0',
          name: 'SUBTYPE',
        },
        {
          value: 'USD',
          name: 'CURRENCY',
        },
      ],

    },
    {
      column: [{
          value: 'W',
          name: 'TYPE',
        },
        {
          value: 'P',
          name: 'STATUS',
        },
        {
          value: '0',
          name: 'SUBTYPE',
        },
        {
          value: 'USD',
          name: 'CURRENCY',
        },
      ],
    },

  ],
};

console.log(compareActualAndExpectedResponse(JSON_1, JSON_2));
Ramaraja
  • 2,526
  • 16
  • 21
  • Thank you so much.. Let me check this and update you..!!! – ArrchanaMohan Aug 28 '20 at 09:27
  • Can you please share the JSfiddle so that I can check with different payloads that I have – ArrchanaMohan Aug 28 '20 at 10:44
  • 1
    Here's a repl.it link, https://repl.it/repls/PureWarpedProgrammingmacro – Ramaraja Aug 28 '20 at 11:17
  • @ArrchanaMohan The code will compare 2 JSON objects for equality, it disregards the order in which array elements appear. Can you provide the example for which it's not giving the expected result? I have shown with the example you've given in the question, it returns true – Ramaraja Aug 28 '20 at 11:20
  • Its working with all the sample that I given in the above link.. but not sure why its not working in nodeJS – ArrchanaMohan Aug 28 '20 at 11:25
  • @ArrchanaMohan Pardon? The code is in JS, I checked locally by running it using Node. The repl.it link I sent is in Node. So, I don't quite understand what you mean by it's not working in Node.JS? – Ramaraja Aug 28 '20 at 11:35
  • I'm debugging this.. Not sure Its not working in my local IDE. May be I missed something.. I just edited my code with latest changes. – ArrchanaMohan Aug 28 '20 at 11:43
  • Let us [continue this discussion in chat](https://chat.stackoverflow.com/rooms/220615/discussion-between-arrchanamohan-and-ramaraja-ramanujan). – ArrchanaMohan Aug 28 '20 at 11:52
  • 1
    Finally it works.. I need to parse the JSON and create a variable and then need to pass it to the function. Thank you so much.. You save a day...It helps a lot. Accepting yours answer – ArrchanaMohan Aug 28 '20 at 12:58