Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Compare two JSON files

I am trying to compare two JSON files in Cypress.

To see if this works I simply made a copy of data.json and renamed its copy to data2.json.

var comparejson = cy.readFile('data2.json')
cy
  .readFile('data.json')
  .then(json => JSON.stringify(json)).should('eq', JSON.parse(comparejson))

This is the error I get:

SyntaxError: Unexpected token o in JSON at position 1
like image 737
ashna naran Avatar asked Sep 05 '26 01:09

ashna naran


1 Answers

Ah, the dreaded token o. It's reading the 'o' from [object Object], which is the toString representation of a Plain Ol' JavaScript Object.

You can test this for yourself, by the way, by entering a JavaScript REPL and:

08:54 $ node
Welcome to Node.js v13.0.1.
Type ".help" for more information.
> JSON.parse({}.toString())
Thrown:
SyntaxError: Unexpected token o in JSON at position 1
> ({}).toString()
'[object Object]'

So in the future, any time you see that error you know you've skipped a step in stringifying somewhere!

The trick here is that readFile returns an object (not a string, JSON files are parsed by Cypress into JavaScript) but you're calling JSON.parse on the object.

Try this:

cy
  .readFile('data2.json')
  .then(data2 => cy.readFile('data.json').should('deep.equal', data2))

Note use of deep.equal here, since we're comparing objects.

like image 54
Rich Churcher Avatar answered Sep 07 '26 13:09

Rich Churcher