在Cypress中通过变量动态获取JSON二级嵌套属性值
解决Cypress中动态读取JSON二级属性的问题
给定如下JSON结构:
{ "width": 700, "height": 1382, "dataID": { "id1": "54321", "id2": "12345" } }
使用Cypress的cy.readFile()方法时,固定属性名的写法可以正常获取值:
cy.readFile(pathToConfigFile).then(($file) => { const id1value = $file.dataID.id1; });
一级属性可以通过方括号语法动态访问:
cy.readFile(pathToConfigFile).then(($file) => { const customVariable = "dataID"; const id1value = $file[customVariable]; });
但二级嵌套属性直接拼接路径会返回undefined,正确的做法是对每一级动态属性单独使用方括号,示例如下:
方法1:直接动态指定二级属性
cy.readFile(pathToConfigFile).then(($file) => { // 动态定义要获取的二级属性名 const targetId = "id1"; // 可根据需求替换为"id2"或其他变量 const idValue = $file.dataID[targetId]; // 后续使用idValue });
方法2:两级属性都动态指定
如果一级属性也需要动态切换,同样用方括号逐层访问:
cy.readFile(pathToConfigFile).then(($file) => { const sectionKey = "dataID"; const targetId = "id2"; const idValue = $file[sectionKey][targetId]; // 后续使用idValue });
错误写法说明
不要尝试将多级属性路径拼成单个字符串放入方括号(比如$file["dataID.id1"]),这种写法会在JSON中查找名为dataID.id1的一级属性,而该属性不存在,因此返回undefined。
内容的提问来源于stack exchange,提问作者Valeriia
相关产品推荐
相关产品推荐

