[英]Big Json parsing in cypress, jsonPath usage
我是柏樹的新手,在嘗試處理 json 響應時遇到問題。 我得到帶有單位結構(樹結構)的 json,我需要從中獲取所有名稱。
我嘗試使用 jsonpath dependenc 並使用 jp.query 解析 json,但它不起作用:
cy.request(*some request*).its('body').then((body) => {
let units = jp.query(body, "$..[?(@.type=='PROJECT')].name");
})
我得到obj needs to be an object Assertion error here
如何解決這個問題,或者還有其他方法可以在柏樹中解析 json?
JSON 樣品:
[
{
"id": 2,
"name": "Solar",
"children": [
{
"id": 3,
"name": "Earth",
"children": [
{
"id": 4,
"name": "Moon",
"type": "STREAM",
"active": true
}
],
"type": "PROJECT",
"active": true
},
{
"id": 5,
"name": "Jupiter",
"children": [
{
"id": 6,
"name": "Io",
"type": "STREAM",
"active": true
},
{
"id": 7,
"name": "Ganymede",
"type": "STREAM",
"active": true
}
]},
],
"type": "PROGRAM",
"active": true
},
{
"id": 9,
"name": "Centaurus",
"children": [
{
"id": 10,
"name": "Alpha Centauri A",
"children": [
{
"id": 818,
"name": "Alpha Centauri Aa-2345",
"type": "STREAM",
"active": true
}
],
"type": "PROJECT",
"active": true
},
{
"id": 11,
"name": "Alpha Centauri B",
"children": [
{
"id": 12,
"name": "Alpha Centauri Bb",
"type": "STREAM",
"active": true
}
],
"type": "PROJECT",
"active": true
},
],
"type": "PROGRAM",
"active": true
}
]
在jp.query()
之前添加以下兩行
body = JSON.stringify(body);
body = JSON.parse(body);
根據請求/響應的配置方式,您可能會遇到以下問題之一
body
是一個字符串body
cy.request(*some request*)
.then(response => response.json())
.its('body')
.then(body => {
let units = jp.query(body, "$..[?(@.type=='PROJECT')].name");
})
或者
cy.request(*some request*)
.its('body')
.then(body => body.json())
.then(body => {
let units = jp.query(body, "$..[?(@.type=='PROJECT')].name");
})
或者
cy.request(*some request*)
.then(response => response.json())
.then(jsonObj => {
let units = jp.query(jsonObj, "$..[?(@.type=='PROJECT')].name");
})
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.