简体   繁体   English

比较两个 JSON 文件

[英]Compare two JSON files

I am trying to compare two JSON files in Cypress.我正在尝试比较赛普拉斯中的两个 JSON 文件。

To see if this works I simply made a copy of data.json and renamed its copy to data2.json .为了看看这是否有效,我只是复制了data.json并将其副本重命名为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

Ah, the dreaded token o .啊,可怕的token o It's reading the 'o' from [object Object] , which is the toString representation of a Plain Ol' JavaScript Object.它正在从[object Object]读取“o”,这是普通 Ol' JavaScript Object 的toString表示。

You can test this for yourself, by the way, by entering a JavaScript REPL and:顺便说一句,您可以自己测试这个,方法是输入 JavaScript REPL 并:

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. 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.注意这里使用deep.equal ,因为我们是在比较对象。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM