How can I display the objects of an array from an API? - node.js

I have an array with 100 objects from an API, every object has an "user Id" key.
The array is something like:
[{ "userId": 1,
"id": 1,
"title": "sunt aut facere repellat provident occaecati excepturi optio reprehenderit",
"body": "quia et suscipit\nsuscipit recusandae consequuntur expedita et cum\nreprehenderit molestiae ut ut quas totam\nnostrum rerum est autem sunt rem eveniet architecto"
},
{
"userId": 1,
"id": 2,
"title": "qui est esse",
"body": "est rerum tempore vitae\nsequi sint nihil reprehenderit dolor beatae ea dolores neque\nfugiat blanditiis voluptate porro vel nihil molestiae ut reiciendis\nqui aperiam non debitis possimus qui neque nisi nulla"
}, etc ]
How can I display all the objects in console? After this I have to search in array for a specific userId introduced by the user in the main page of application, I use express, body-parser, https from node.js.
app.post("/", function(req, res){
var userId = req.body.userId;
console.log(userId);
});

How can I show all the objects in console?
Assuming that you receive the array a variable name apiResults
console.log(apiResults) //or
console.log(JSON.stringify(apiResults))
I have to search in array for a specific userId..?
Use the Array.protype.some method to return a specific item from an array
var specificUser = apiResults.some(item => item.userId === preferedUser);

Related

Loop through Items returned from an API Call and save them in array variable

I have a a REST API that when I call with GET for example from a browser I get a proper response like:
[
{"name": "jack",
"id" : 23
},
{"name": "joe",
"id" : 45
},
{"name": "james",
"id" : 56
}
]
So now in ADF I add a Web Activity and call the same API.
If at all possible: I want to have those items from the response in a array variable so I can loop through them.
How do I do this?
I have created a Set Variable activity and connected to output of my WebAPI call like picture below
and my pipeline variable is called apiCallOutput with type of Array.
Looking in Pipeline Run, the output of the Web APICall is like this:
{
"Response": "[
{"name": "jack",
"id" : 23
},
{"name": "joe",
"id" : 45
},
{"name": "james",
"id" : 56
}
]",
"typicalMetaData" : "stuff That Azure adds"
}
The following is a demonstration of how you can loop through items (and use its values) from the response which is returned using Web activity.
The following is the data that would be returned by my sample web activity (a sample provided, there are 100 items in total). I am just retrieving just userId and title for demonstration.
[
{
"userId": 1,
"id": 1,
"title": "sunt aut facere repellat provident occaecati excepturi optio reprehenderit",
"body": "quia et suscipit\nsuscipit recusandae consequuntur expedita et cum\nreprehenderit molestiae ut ut quas totam\nnostrum rerum est autem sunt rem eveniet architecto"
},
{
"userId": 1,
"id": 2,
"title": "qui est esse",
"body": "est rerum tempore vitae\nsequi sint nihil reprehenderit dolor beatae ea dolores neque\nfugiat blanditiis voluptate porro vel nihil molestiae ut reiciendis\nqui aperiam non debitis possimus qui neque nisi nulla"
}
]
You can directly use the Response in For Each activity. For items field in the for each activity, you can use the following dynamic content.
#json(activity('Web1').output.Response)
Now you can access the item values inside the for each loop with 2 set variable activities. (provided dynamic content for your case)
#to get name value
#string(item().name)
#to get id value
#string(item().id)
Now when you debug the pipeline, you can see that the required values will be retrieved.
The output for value1 set variable activity.
The output for value2 set variable activity.
This way you can assign the item values into variables (String type) and use them inside for each directly.
NOTE:
You can directly use the values of an item as #item().name and #item().id without using set variable activity activity as well.

axios get response is junk

I am using axios to fetch some data from typicode api.
The result I am getting is some junk like this.
// apis.js
const axios = require('axios');
const getRequest = async () => {
const res = await axios.get('https://jsonplaceholder.typicode.com/posts/1');
console.log(res.data);
}
getRequest();
I am running this code using command node apis.
I am expecting result as below, as shown mentioned at https://jsonplaceholder.typicode.com/posts/1
{
"userId": 1,
"id": 1,
"title": "sunt aut facere repellat provident occaecati excepturi optio reprehenderit",
"body": "quia et suscipit\nsuscipit recusandae consequuntur expedita et cum\nreprehenderit molestiae ut ut quas totam\nnostrum rerum est autem sunt rem eveniet architecto"
}
The code is completely fine and works on my machine. This must be a problem with your environment. Are you inside a VPN of a company or make this call from a server that sits in a special network or anything like that?

Dealing with object return from axios

Someone could please point me what I need do to get the nuxt axios return which works inside vuetify v-for?
I'm using the following code:
async asyncData() {
let res = await axios.get('https://jsonplaceholder.typicode.com/posts')
console.log(res)
let objectPosts = {}
objectPosts = res.data
return (posts: objectPosts)
},
My componnent data is:
data() {
return {
posts: {}
}
},
My v-for is:
<article v-for="(post, index) in posts" :key="index">
And the error I'm getting is:
[Vue warn]: Error in render: "TypeError: Cannot read properties of undefined (reading 'length')"
If I fill my componnent data with the json as object manually works fine, example:
data() {
return {
posts: [
{
"userId": 1,
"id": 1,
"title": "sunt aut facere repellat provident occaecati excepturi optio reprehenderit",
"body": "quia et suscipit\nsuscipit recusandae consequuntur expedita et cum\nreprehenderit molestiae ut ut quas totam\nnostrum rerum est autem sunt rem eveniet architecto"
},
{
"userId": 1,
"id": 2,
"title": "qui est esse",
"body": "est rerum tempore vitae\nsequi sint nihil reprehenderit dolor beatae ea dolores neque\nfugiat blanditiis voluptate porro vel nihil molestiae ut reiciendis\nqui aperiam non debitis possimus qui neque nisi nulla"
}
]
}
},
Console log show the array from axios too.
The application is using SSR, my initial guess was on be an issue with async, page get rendered first and object don't exists triggering this error.
Since its a list of objects shouldn't it be like this? :
data() {
return {
posts: {[]}
}
},
After read a lot of similar situations here and on social networks, have found this one:
Object assignment in Vue.js method
Then I have tried make the default values for component data like docs sayed to do:
https://v2.vuejs.org/v2/guide/reactivity.html?redirect=true#Declaring-Reactive-Properties
Other errors come out.
After some tries debugging (removing items from object one by one), have found in the original component there a lot of v-for and nuxt-link.
Inside v-for will drop errors on some situations.
Inside nuxt-link will not accept null (empty default object) or blank values.
Conclusion:
Seems I will need validate the entire object / array always and in the end force an Object.assign. Since I haven't made the API yet, solution will be hardcode an json file to read local.
You need to change the type of your posts to Array []

Azure cognitive search indexer indexes from Blob storage but doesn't strip the markup of XML content

As said in the title I am trying to index XML files from blob storage using an Indexer however the indexed files still contain the XML markup instead of being parsed and stripped of tags.
The following XML is an example of the XML code I am trying to index:
<article xmlns="http://ournamespace.com/ns/test" xmlns:xlink="http://www.w3.org/1999/xlink">
<title>Lorem ipsum</title>
<section>
<para> Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. (<link xlink:href="f8c79a4d-f1f1-4d8d-ab4c-d9317754465e"> Ut enim ad minim veniam</link>). quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat.</para>
</section>
<section>
<title>
<emphasis role="strong"> Duis aute irure dolor in reprehenderit in voluptate velit esse</emphasis>
</title>
<itemizedlist mark="square">
<listitem>
<para>
<link xlink:href="d1cce80e-835f-4b37-892e-54bba282f437">cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt</link> in culpa qui officia deserunt mollit anim id est laborum. </para>
</listitem>
</itemizedlist>
</section>
</article>
I have made sure that the content-type of the blob is application/xml and that the indexer parsing mode is default since I read in this question that this is crucial to being able to parse the document properly.
This is the indexer configuration:
{
"#odata.context": "https://<redacted>.search.windows.net/$metadata#indexers/$entity",
"#odata.etag": "\"0x8D7D7C7CF735BF4\"",
"name": "azureblob-indexer",
"description": "",
"dataSourceName": "blob-indexer",
"skillsetName": null,
"targetIndexName": "<redacted>-index",
"disabled": null,
"schedule": null,
"parameters": {
"batchSize": null,
"maxFailedItems": 0,
"maxFailedItemsPerBatch": 0,
"base64EncodeKeys": null,
"configuration": {
"dataToExtract": "contentAndMetadata",
"parsingMode": "default"
}
},
"fieldMappings": [
{
"sourceFieldName": "metadata_storage_path",
"targetFieldName": "metadata_storage_path",
"mappingFunction": {
"name": "base64Encode"
}
},
{
"sourceFieldName": "Subscriptions",
"targetFieldName": "Subscriptions",
"mappingFunction": {
"name": "jsonArrayToStringCollection"
}
}
],
"outputFieldMappings": [],
"cache": null
}
The indexed document display the following metadata which I find weird since the content_type suddenly changes from one type to another. I assume that this means that the parsingmode used for this document was text?
{
"metadata_storage_content_type": "application/xml",
"metadata_content_encoding": "UTF-8",
"metadata_content_type": "text/plain; charset=UTF-8"
}
This is information about one of the blobs that are being indexed:
LAST MODIFIED 4/2/2020, 3:28:13 PM
CREATION TIME 4/2/2020, 3:28:13 PM
TYPE Block blob
SIZE 27.94 KiB
ACCESS TIER Hot (Inferred)
ACCESS TIER LAST MODIFIED N/A
SERVER ENCRYPTED true
ETAG 0x8D7D709B1C7C5D5
CONTENT-TYPE application/xml
CONTENT-MD5 3yeFKKcSGh/6DJawrAWaWg==
LEASE STATUS Unlocked
LEASE STATE Available
LEASE DURATION -
COPY STATUS -
COPY COMPLETION TIME -
Any help would be greatly appreciated and I am of course willing to provide more information if necessary. thanks in advance!

Tabulator mutator doesn't display any data

Given the following table description:
<script>
var customMutator = function(value, data, type, params, component){
return data.category_name + " " + data.short_description;
} ;
var tabledata = [
{id:1, category_name:"IT", short_description:"This is an IT message", long_description:"Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat.", valid_from:"2019-12-05T10:48:00", valid_to:"2018-12-04T22:00:00"},
{id:2, category_name:"Bookeeping", short_description:"This is an bookeeping message", long_description:"Lorem ipsum dolor azaz sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat.", valid_from:"2019-12-04T10:48:00", valid_to:"2019-12-04T22:00:00"},
];
var printIcon = function(cell, formatterParams, onRendered){
return '<span style="color:blue;"><i class="far fa-edit"></i></span>';
};
var table = new Tabulator("#mb-table", {
placeholder:"Keine Nachricht vorhanden...",
height: window.innerHeight - 53,
layout:"fitColumns",
langs:{
"de-de":{
"headerFilters":{
"default":"Filtern..."
}
}
},
columns:[
{title:"Kategorie", field:"category_name", headerFilter:true, width:120},
{title:"Kat", field:"new_kat", mutator:customMutator, headerFilter:true, width:120},
{title:"Nachricht", field:"short_description", headerFilter:true, formatter:function(cell, formatterParams){
var val1 = cell.getValue();
var val2 = cell.getRow().getData().long_description;
cell.getElement().style.whiteSpace = "pre-wrap";
return "<span style='font-weight:bold;'>" + val1 + "</span><br><span style='word-break: normal;'>" + val2 + "</<span>";
}
},
{title:"Gültig von", field:"valid_from", headerFilter:true, width:110, sorter:"datetime", sorterParams:{format:"YYYY-MM-DDThh:mm:ss"},
formatter:"datetime", formatterParams:{
inputFormat:"YYYY-MM-DDThh:mm:ss",
outputFormat:"DD.MM.YYYY hh:mm"
},
},
{title:"Gültig bis", field:"valid_to", headerFilter:true, width:110, sorter:"datetime", sorterParams:{format:"YYYY-MM-DDThh:mm:ss"},
formatter:"datetime", formatterParams:{
inputFormat:"YYYY-MM-DDThh:mm:ss",
outputFormat:"DD.MM.YYYY hh:mm"
},
},
{formatter:printIcon, align:"center", width:10, headerSort:false,
cellClick:function(e, cell){alert("Printing row data for: " + cell.getRow().getData().id)}},
{formatter:"buttonCross", width:10, align:"center", headerSort:false,
cellClick:function(e, cell){alert("Printing row data for: " + cell.getRow().getData().category_name)}},
]
});
table.setLocale("de-de");
table.setData(tabledata);
</script>
I do not see anything displayed in the Kat column.
What am I doing wrong?
EDIT:
Actually the mutator function is not even invoked.
If I place console.log(data); (before the return, of course) into the function I cannot see anything in the console
upgrading to V. 4.5.3 has solved that issue.

Resources