I cannot quite figure out how to access the 0th element in the array as part of the JSON body in order to check the API response. I have tried various ways and none seem to be correct.
I currently have the following as an example:
I'm guessing it is not difficult but for the life of me I can't figure it out. Thanks!
cy.get('#dogs')
.its('body')
.its('breeds[0]')
.its('names')
.should('include', {
count: ('10'),
});
Refer its. The indexes should be accessed individually with its.
Response JSON:
{
"sample": [
{ "names": ["Dummy 1", " Dummy 2"] },
{ "names": ["Dummy 3", " Dummy 4"] },
{ "names": ["Dummy 5", " Dummy 6"] }
]
}
The last object in the array should be accessed as:
// to check a child's length
cy.get('#sample')
.its('body') // 'responseBody' in case of latest cypress version
.its('sample')
.its('2')
.its('names')
.its('length')
.should('eq', 2);
// To check content
cy.get('#sample')
.its('body') // 'responseBody' in case of latest cypress version
.its('sample')
.its('2')
.its('names')
.its(1)
.should('include', '6');
Screenshot:
Related
I have done this before, but I am not sure what error I am making here in order to populate the select drop down with options retrieved from JSON response. The API call is successfull and I can see the data pulled but not able to display it in options of select drop down.
varibale in concern is idsFetched
let idsFetched = this.state.storeRanges.Stores
console.log("ranges I/O ", idsFetched);
let options3 = idsFetched.map(store => {
return {value: store.value.description, label: store.value.description};
})
---- JSON RESPONSE ---- Stored in variable = storeRanges
{
"Stores": [
{
"mode": "LOADED",
"value": {
"description": "Ontario-Example-123",
}
},
{
"mode": "LOADED",
"value": {
"description": "Ontario-Example-456",
}
},
{
"mode": "LOADED",
"value": {
"description": "Ontario-Example-789",
}
},
]
}
First make sure you have done JSON.parse(apiResponse) otherwise you'll just be storing a string, making storeRanges.Stores === undefined probably causing your issue.
Secondly, make sure the State has been set first, by wrapping the function in a check. If you've done it correctly the re-render after setting state should fire it off no worries
I was able to fix the issue by declaring an empty variable in state and then updating the state in ComponentDidUpdate hook and accessing that in onChange method.
componentDidUpdate(prevProp, prevState){
this.setState({idsFetched: this.state.storeRanges.Stores})
}
onChange(){
options = ranges.map(range => {
return {value: range.value.description, label: range.value.description};
})
}
This is how I could access the array of stores fetched from JSON response!
Thank you everyone for looking into my query!
I'm trying to get each of of the values inside my JSON file but when I run my API I get [Object Object] instead of what is inside the JSON.
This is my API request:
getAllvalues(): Observable<string[]> {
return this.http
.get<string[]>(this.Url + 'api');
}
my component.ts
this.ddvService.getAllvalues()
.subscribe(response => {
this.slots = response;
console.log (this.slots)
});
Example of my JSON response:
[
{
"AB": "http:"
},
{
"DE": "http:"
},
{
"CE": "http:"
},
{
"HI": "http:"
}
]
How can I get the value inside the JSON, and create a dropdown box with each of them?
Your example JSON is a pretty bad example: each object in the array in the JSON should have at least somewhat matching key names. In your case, the keys are "AB", "DE", "CE", "HI" - all different, which is quite uncommon in real-life. A more realistic JSON response would have matching key names, e.g.:
[
{
"id": "1",
"description": "Some description"
},
{
"id": "2",
"description": "Another description"
}
]
Now to answer your questions:
You are getting [Object Object] because you are trying to use an entire object as a literal value. Instead, you should access the individual keys/values of an object. For example: console.log(slots[0].id) - this should output 1.
Also, as indicated in the comments, replace Observable<string[]> with Observable<any[]> and get<string[]> with get<any[]>.
To create a drop-down in Angular, in your component template you can try this, assuming your slots value is the JSON above:
<select *ngIf="slots" name="slots">
<option *ngFor="let slot of slots" value="slot.id">{{ slot.description }}</option>
</select>
Also, to print the entire object to console in a readable form, instead of just console.log(this.slots);, you can try console.log(JSON.stringify(this.slots));
As mentioned in the comments above it is not ideal to have json like you have, my assumption is you might want to log keys instead of values, since value is same for all the objects in array. In that case you might want to try something like this.
1. Add any[] instead string[].
2.Add nested for loop to console.log your object array.
getAllvalues(): Observable<string[]> {
return this.http
.get<any[]>(this.Url + 'api');
}
this.ddvService.getAllvalues()
.subscribe(response => {
this.slots = response;
for(let i in this.slots)
{
let currentObj = this.slots[i]; // example of first in array { AB : "http:"}
for ( let z in currentObj )
{
if(currentObj[z]=== "http:") // we are trying to find key instead value
{
console.log(z); // it will log AB, DE, CE, HI ..
}
}
}
});
I've been wondering for some days what kind of scheme would be more appropriate to use a data list in json in a web application.
I'm developing a REST Web Application, and im using Angular for front end, i should order, filter and print these data list also in xml ...
For you what scheme is better and why?
1) {
"datas": [
{ "first":"","second":""},
{ "first":"","second":""},
{ "first":"","second":""}
]
}
2) {
"datas": [{
"data": { "first":"","second":""},
"data": { "first":"","second":""},
"data": { "first":"","second":""}
}]
}
3) [
{ "first":"","second":""},
{ "first":"","second":""},
{ "first":"","second":""}
]
Thanks so much.
The first and third notations are quite similar because the third notation is included in your first.
So the question is "Should I return my datas as an array or should I return an object with a property that contain the array ?
It will depend on either you want to have more information alongside your datas or not.
For exemple, if your API might return an error, you will want to manage it from the front end.
In case of error, the JSON will looks like this :
{
"datas": null,
"error": "An error occured because of some reasons..."
}
At the opposite, if everything goes well and your API actually return the results, it will looks like this :
{
"datas": [
{ "first":"","second":""},
{ "first":"","second":""},
{ "first":"","second":""}
],
"error": null
}
Then your front end can use the error property to manage errors sent from the API.
var result = getDatas(); // Load datas from the API
if(result.error){
// Handle the error, display a message to the user, ...
} else {
doSomething(result.datas); // Use your datas
}
If you don't need to have extra properties like error then you can stick with the third schema.
The second notation is invalid. The datas array will contain only one object which will have one property named data. In this case data is a property that is defined multiple times so the object in the array will contain only the last occurence:
var result = {
"datas": [{
"data": { "first":"a","second":"b"},
"data": { "first":"c","second":"d"},
"data": { "first":"e","second":"f"}
}]
}
console.log("Content of result.datas[0].data : ")
console.log(result.datas[0].data)
Obviously the first option would be easy to use. Once you will access datas it'll give you an array. Any operation (filter, sort, print) on that array will be easy in comparison to anything else. Everywhere you just need to pass datas not datas.data.
I would like to configure sync between two different CRMs (Clevertap and Intercom) using Zapier and Webhooks. In general Clevertap sends the following JSON to webhook:
{
"targetId": 1548328164,
"profiles": [
{
"event_properties": {
"MSG-sms": true,
"MSG-push": true,
"businessRole": "EMPLOYEE",
"Mobile Number": "123123123123",
"Name": "Artem Hovtvianisa",
"Title": "Mr",
"Last Name": "Hovtvianisa",
"Gender": "M",
"Customer type": "Business Account Holder",
"MSG-email": true,
"First Name": "Artem",
"Last seen IP": "111.177.74.50",
"tz": "GMT+0200",
"International customer": "yes",
"isBusiness": true,
"Email": "xxxyyy#gmail.com",
"Identity": 15675
},
"objectId": "e32e4de3c1e84b2d9bab3707c92cd092",
"all_identities": [
"15675",
"xxxyyy#gmail.com"
],
"email": "xxxyyy#gmail.com",
"identity": "15675"
}
]
}
Zapier provides two types of catch webhook: regular and Raw.
Catch Raw Hook
When I use this type, JSON raw data will be handled OK and on the next step (Zapier JS code app) I am able to pass proper JSON data like in example above.
However when I use simple JS code to parse JSON object and get profiles[0] array value I get the following error "TypeError: Cannot read property '0' of undefined"
JS Code from Code step:
var result = JSON.parse(JSON.stringify(inputData));
console.log(result.profiles[0]);
return result;
Catch Hook
In case I use regular Catch Hook, hook parse data in some odd way, like this:
JSON.parse cannot recognize this structure.
Please advise how can I handle Webhook Zapier step in a proper way in order to get profiles[0] array item values?
Thanks in advance!
David here, from the Zapier Platform team. You're on the right track!
Catch Raw Hook is the way to go here. Your issue is that the data is coming in as a string and you're re-stringifying it before parsing it, which gets you back to where you came from. A simpler version:
JSON.stringify("asdf") // => "\"asdf\"", quotes in the string
JSON.parse("\"asdf\"") // => "asdf", the original string
"asdf".profiles // => undefined
undefined[0] // => error, cannot read property "0" of undefined
Instead, just parse it and you're good to go!
// all your variables are already in "inputData", so yours,
// also named inputData, must be referenced explicitly.
const result = JSON.parse(inputData.inputData);
return {result: result, firstProfile: result.profiles[0]};
I am decently new to Lua, an I have been trying to work on API calling JSON tables. However, one particular JSON Table I am trying to process has identifiers that start with numbers. For example, one such table looks like this:
"data": {
"1001": {
"plaintext": "item title",
"description": "item description",
"id": 1001
}
}
When I try to decode the json file and print "data.1001.id" to the console, for example, I keep getting an error "malformed number near '.1001.id'".
I've looked at other similar questions on this site that say to put it in square brackets, such as "data.[1001].id" or "data.[[1001]].id", but when I do that I get the error " 'name' expected near '[[1001]]'".
Any help would be appreciated
You can use normal access as an array element []:
local json = require("json")
local j=[[
{
"data": {
"1001": {
"plaintext": "item title",
"description": "item description",
"id": 1001
}
}
}
]]
local d = json.decode(j)
print(d.data["1001"].description)