Get data from array in JSON API object in Cypress - json

Relative newbie to Cypress and JSON data. I have an api online that I can access. The api has data similar to this:
{"record":[{"account":"acount_1","team":"Test 1","req_id":12345},{"account":"acount_2","team":"Test 2","req_id":23456}],"metadata":{"id":"abcde","private":false,"createdAt":"2022-12-21T00:00:00.000Z"}}
I am attempting to find a manner to get the amount of records that are in the api, as well as get the first team name.
The closest I have come to getting any kind of data is by using something like this:
cy.get('#testing').then((data) => {
for (let index in data)
cy.log(data[index])
})
However, all that does is show me what is in the API, not the data in the array itself. I have attempted dozens of different options, none of which has worked. I hope someone can please help me!

Assuming your intercept was waited on with the alias and the data is nested as you say in the respon, you can access the response JSON data
cy.get('#testing')
// get records and check length
.its('record')
.should('have.length', 2)
// get first team name
.its('0.team')
.should('eq', 'Test 1')
Here is a working example.

Related

How can I pass the document sub-collections along with the document JSON map in Flutter using Firebase?

I'm trying to get all the documents in the "businesses" collection from Firebase together with their sub-collections.
The problem is when I do the query to Firebase like this :
Stream<List<Business>> getBusinesses() {
return _db.collection('businesses').snapshots().map((snapshot) => snapshot
.docs
.map((document) => Business.fromJson(document.data()))
.toList());
}
, the sub-collections aren't passed with the JSON object document.data(), so in my code, the Business object isn't fully completed, which means there are empty fields (Appointments, ServiceProviders,
Services), instead of getting the data from the sub-collections.
So hopefully I've explained the problem well, my question is how can I fetch all the document data including its sub-collections, and parse it to a Business Object?
Thanks.
What seems to be "the problem" is actually the point of Firestore: Keeping documents shallow so you can only get the data you need. It's then up to you to structure your data the way it will likely be used in the future.
Mind you, subcollections are not fields.
What you can do here, is add a query that fetches the documents in the subcollections (Appointments, ServiceProviders, Services), for each business. You would get the business document Id to use for the query.
It would typically look something like:
_db.collection('businesses').document(documentId).collection('Appointments')
Mind you, this is potentially too much data. It might be better to fetch the docs in those subcollections only when needed/requested by the user.

Writing data from MATLAB to firebase database

I am using MATLAB to write data from MATLAB to firebase. I am using following lines of code to do so:
thingSpeakURL = 'https://hybrid-cabinet-265907.firebaseio.com/Ship A/Time Stamp.json';
lat = num2str(42);
lon = num2str(42);
data = struct('lat',lat,'lon',lon);
webwrite(thingSpeakURL,data)
Data is successfully written to Firebase. It is making my original JSON data as a child to a random string been generated on run-time.
For example, my JSON string is {lat: '40',lon:'40'} but instead it is creating a random string, let say, "Mxkkllslsll-1112", making that random string as parent and writing something like {"Mxkkllslsll-1112": lat:'40', lon:'40'} to the firebase database.
Please have a look at following image. It shows that for ship A, I have written data from MATLAB and it is not writing properly(I am facing the problem which I discussed above). I want to make it something like data written for Ship B.
I want to write the data without making any random string as a parent. Kindly assist me in that.
This is because webwrite uses the HTTP POST method by default.
As shown in the Firebase Realtime Database REST API documentation, if you do a POST you will push the data and therefore automatically generate a unique key every time a new child is added to the specified Firebase reference (the -MDJVMk..... value we can see in your question).
You need to use the PUT method.
I don't know matlab but a rapid look at the documentation shows that you need to use the RequestMethod option with a put value, in the weboptions object.
The above pushed me in the right direction (thanks!), and I had success with the following.
CAUTION: The following will overwrite everything in your database!
url = 'https://***.firebaseio.com/.json';
data.users(1) = struct('first','John','last','Locke');
data.users(2) = struct('first','Thomas','last','Hobbes');
data.users(3) = struct('first','Rene','last','Descartes');
headers = {'Content-Type' 'application/json'; 'Accept' 'application/json'};
options = weboptions('RequestMethod', 'put', 'HeaderFields', headers, 'ArrayFormat', 'json');
response = webwrite(url, data, options);
If your data is stored in a .json file (i.e., you don't want to create structures manually in Matlab), you can read it using "fileread" and pass in data as a string (instead of a structure).

receive Excel data and turn into objects to format a JSON

I have this solution that helps me creating a Wizard to fill some data and turn into JSON, the problem now is that I have to receive a xlsx and turn specific data from it into JSON, not all the data but only the ones I want which are documented in the last link.
In this link: https://stackblitz.com/edit/xlsx-to-json I can access the excel data and turn into object (when I print document.getElementById('output').innerHTML = JSON.parse(dataString); it shows [object Object])
I want to implement this solution and automatically get the specified fields in the config.ts but can't get to work. For now, I have these in my HTML and app-component.ts
https://stackblitz.com/edit/angular-xbsxd9 (It's probably not compiling but it's to show the code only)
It wasn't quite clear what you were asking, but based on the assumption that what you are trying to do is:
Given the data in the spreadsheet that is uploaded
Use a config that holds the list of column names you want returned in the JSON when the user clicks to download
based on this, I've created a fork of your sample here -> Forked Stackbliz
what I've done is:
use the map operator on the array returned from the sheet_to_json method
Within the map, the process is looping through each key of the record (each key being a column in this case).
If a column in the row is defined in the propertymap file (config), then return it.
This approach strips out all columns you don't care about up front. so that by the time the user clicks to download the file, only the columns you want are returned. If you need to maintain the original columns, then you can move this logic somewhere more convenient for you.
I also augmented the property map a little to give you more granular control over how to format the data in the returned JSON. i.e. don't treat numbers as strings in the final output. you can use this as a template if it suites your needs for any additional formatting.
hope it helps.

Problems getting specific data out of response from ajax call

The json file I am calling can be found here. It contains population data for regions in Ghent (a city in Belgium) during a specific year. I use the following code to retrieve the data, the array where i store the response data is called "inwonersperwijk":
function(key,value) {
$.each(key,function(key,value){
inwonersperwijk.push(value);
});
$.each(key[0], function (key, value) {
years.push(key);
});
}
,
error: function(er){
console.log(er);
}});
which returns an object that looks like this.
What I am trying to do is retrieve the "wijk" in each of these objects. When I try to use inwonersperwijk[0].year_1999 for example, it returns the corresponding data just fine.
But when I want to retrieve the "wijk" part of the data by using inwonersperwijk[0].wijk, I get an undefined. Could anyone possibly help me out with this?
Looking at your JSON source file I can see that the indexes for the years are "year_1999", "year_2000" and so on, but the index for the wijk is actually "\ufeffwijk". The \ufeff is a non-breaking space (see here).
If you look at your output array screenshot, you will see that the year indices have no quotes, while the index for wijk does (it's "wijk" not wijk). This is why you get undefined: the index for wijk does not actually exist.
You're better off first filtering the \ufeff characters out of the JSON before parsing it.

printing JSON values in Python

I've search a ton of articles here and elsewhere via the Googles, plus read a few related docs over at docs.python.org and still stuck.
I am getting a response from an API like below:
{"status":"active","perms":1,"data":{"40332895":{"user_values":{"delta":-203,"value":53.32,"order":42509}}}}
I have no problem printing the 'status' or 'data'. However, all I can grab is the name of the *user_values*, not the date inside them.
Been at it for way to long and was hoping someone could point me in the right direction. Fairly new to Python and if I need to change how I am doing this because it is bad practices or there is an easier way to get the results I am looking for, please let me know.
Code:
import json
import urllib2
url = urllib2.urlopen('http://URLofAPI.com')
json_url = json.load(url)
api_result = json_url
for doc in api_result['data']['40332895']['user_values']:
print doc
outputs:
delta
value
order
what I really want to get is the value of them (i.e.: '-203', '53.32', '42509').
I am basically trying to save that data into a list\dict (individually or separately), then print it with other data. I have tried all sorts of things and cannot manage it. I am sure it's probably something super easy that I missing, but it's driving me nuts. :)
Also, I was really expecting the below to give me '42509', but I get an error:
for doc in api_result['data']['40332895']['user_values']['order']
Thanks in advance!
You're asking for the keys of the user_values dictionary, and getting them. Try this:
uv = api_result['data']['40332895']['user_values']
for doc in uv:
print uv[doc]
In your example api_result['data']['40332895']['user_values'] is a dictionary.
If you iterate over a dictionary you will get the keys. This is the case in your original example and in mgkrebbs answer.
However if you iterate over the .iteritems() (or .items()) of the dictionary you get the (key, value) pairs in a tuple:
uv = api_result['data']['40332895']['user_values']
for key,value in uv.iteritems():
print key, value
If you only need the values, you iterate over .itervalues()
uv = api_result['data']['40332895']['user_values']
for value in uv.itervalues():
print value
Or if you only need the values as a list:
my_list = api_result['data']['40332895']['user_values'].values()
The difference between .itervalues() and .values() is that the former gives you an iterable (an object which returns one value at a time, but does not create the structure in memory), while the latter gives you a list.