I'm new to cypress and I face a problem when trying to work with json responses. I am getting json with units structure(tree structure) and I need to get all the names from it.
I tried to use jsonpath dependenc and parse json using jp.query, but it doesn't works:
cy.request(*some request*).its('body').then((body) => {
let units = jp.query(body, "$..[?(@.type=='PROJECT')].name");
})
I'm getting obj needs to be an object Assertion error here
How to fix this or maybe there are any other ways to parse json in cypress?
JSON Sample:
[
{
"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
}
]
add below 2 lines before jp.query()
body = JSON.stringify(body);
body = JSON.parse(body);
Depending on how the request/response is configured, you may have one of the following issues
body
is a string body
cy.request(*some request*)
.then(response => response.json())
.its('body')
.then(body => {
let units = jp.query(body, "$..[?(@.type=='PROJECT')].name");
})
or
cy.request(*some request*)
.its('body')
.then(body => body.json())
.then(body => {
let units = jp.query(body, "$..[?(@.type=='PROJECT')].name");
})
or
cy.request(*some request*)
.then(response => response.json())
.then(jsonObj => {
let units = jp.query(jsonObj, "$..[?(@.type=='PROJECT')].name");
})
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.