RadListView and JSON data from a HTTP request - json

I am working on an mobile app that should have a RadListView UI component filled with JSON data procured from an HTTP request. The JSON data that is at the URL address looks like this:
{"dataset": {
"table": [
{
"CustomerNumber": 1,
"Name": "Rudy",
}
}
}
All I get when I try to fill my RadListView with the data is "object Object" times the number of size parameter I request in the URL.
This is how I am trying.
ngOnInit() {
getJSON("http://192.168.10.18:8100/web/data?be=customer&size=5").then(
(r: any) => {
this._dataItems = new ObservableArray(r.dataset.table);
console.log("test: " + r.dataset.table[1]); // test: [object Object]
console.log("test2: " + this._dataItems.length); // test2: 5
},
(e) => {
console.log(e);
}
);
}
Any help is really appreciated as I have been stuck on this for a while and don't really know where to start.

Related

Change JSON structure to send in API post request

I am making an API POST call in Angular 8. I have to send a JSON object in the call which should be of structure:
-{}JSON
-{}data
-[]exp
+{} 0
+{} 1
but I am sending data in this format:
-[]JSON
+{} 0
+{} 1
in my typescript I am getting two objects {}0, {}1 in array called: receivedData then I am storing the data like:
this.changedData = this.receivedData;
this.postService.postMethod(this.headers, this.changedData)
in my postService:
postMethod(header, changedData): Observable<any[]> {
return this.http.post<any>(`the url here`, changedData, {headers: header, responseType: 'text' as 'json'})
.pipe(map(response => {
return response;
}))
}
how to send data in the mentioned format? I want the json structure of changedDetails to be as mentioned on the top with the same naming convention like: {}data and []exp How can I push receivedData objects into exp[] which I can then send into data{} which will then be entirely pushed into changedDetails {}
Just so we're on the same page, I'm imagining you're receiving data with the following shape:
[ { ... }, { ... } ]
And you want to transform it to this shape:
{
data: {
exp: [ { ... }, { ... } ]
}
}
(Let me know if this is not the case.)
If this is correct, than the transformation is quite straightfoward: simply create a new object literal like so:
this.changedData = {
data: {
exp: this.receivedData,
},
};

Access String array in Json

The API I am using has a nested string array it seems, I need to extract the path from it, but I cannot figure out how....
This is a break down of what I need to access.
the productimage is wrapped in quotes...
[
{title: "Item 1",
productimage: "[{"1":{"size":"75x75","path":"/10000/img.jpg"}]"
},
{title: "Item 2",
productimage: "[{"1":{"size":"75x75","path":"/20000/img.jpg"}]"
}
]
I am trying to access the image path...
The problem seems to be reading the string, I have attempted to treat it like an array, and a string and get mixed results..
Edited:
here is the entire productimages object, it is coming from an apache database that i have no control over.
productimages: "[{"1":{"size":"75x75","path":"/100000/101819-75x75-A.jpg"}},{"2":{"size":"222x222","path":"/100000/101819-600x600-A.jpg"}},{"3":{"size":"328x328","path":"/100000/101819-600x600-A.jpg"}}]"
my current axios call looks like this.
async function handleSubmit(searchData) {
if (searchData) {
const payload = searchData;
try {
const response = await axios({
url: `${baseUrl}q=*:*&fq=title:${payload}&fq=storeid:1234
method: "get",
});
//Set Hook
setData(response.data.response.docs);
} catch (error) {
console.error(error);
}
}
}
Here is the response data that is being set..
{productid: 1234, itemups: 1234, title: "productname", productimages: "[{"1":{"size":"75x75","path":"/100000/101819-75x75-A.jpg"}},{"2":{"size":"222x222","path":"/100000/101819-600x600-A.jpg"}},{"3":{"size":"328x328","path":"/100000/101819-600x600-A.jpg"}}]", productcount: 7}
I can get everything out of this, except the image.
You've to parse productimage:
const parsedArray = array.map(obj => {
let path = '';
try {
const productimage = JSON.parse(`${obj.productimage}`);
path = productimage[0].path
} catch(err) {
console.error(err)
}
return { ...obj, path }
});
[EDIT]
Axios response:
axios() // some axios call
.then(res => res.data)
.then(array => {
// ... here you can transform your array
})
Also make sure your json is properly formatted.
{
[
{"title": "Item 1",
"productimage": "[{"1":{"size":"75x75","path":"/10000/img.jpg"}]"
]
}

Elasticsearch js Bulk Index TypeError

Background
Recently, I have been working with the Elasticsearch Node.js API to bulk-index a large JSON file. I have successfully parsed the JSON file. Now, I should be able to pass the index-ready array into the Elasticsearch bulk command. However, using console log, it appears as though the array shouldn't be causing any problems.
Bugged Code
The following code is supposed to take an API URL (with a JSON response) and parse it using the Node.js HTTP library. Then using the Elasticsearch Node.js API, it should bulk-index every entry in the JSON array into my Elasticsearch index.
var APIUrl = /* The url to the JSON file on the API providers server. */
var bulk = [];
/*
Used to ready JSON file for indexing
*/
var makebulk = function(ParsedJSONFile, callback) {
var JSONArray = path.to.array; /* The array was nested... */
var action = { index: { _index: 'my_index', _type: 'my_type' } };
for(const item of items) {
var doc = { "id": `${item.id}`, "name": `${item.name}` };
bulk.push(action, doc);
}
callback(bulk);
}
/*
Used to index the output of the makebulk function
*/
var indexall = function(madebulk, callback) {
client.bulk({
maxRetries: 5,
index: "my_index",
type: "my_type",
body: makebulk
}, function(err, resp) {
if (err) {
console.log(err);
} else {
callback(resp.items);
}
});
}
/*
Gets the specified URL, parses the JSON object,
extracts the needed data and indexes into the
specified Elasticsearch index
*/
http.get(APIUrl, function(res) {
var body = '';
res.on('data', function(chunk) {
body += chunk;
});
res.on('end', function() {
var APIURLResponse = JSON.parse(body);
makebulk(APIURLResponse, function(resp) {
console.log("Bulk content prepared");
indexall(resp, function(res) {
console.log(res);
});
console.log("Response: ", resp);
});
});
}).on('error', function(err) {
console.log("Got an error: ", err);
});
When I run node bulk_index.js on my web server, I receive the following error: TypeError: Bulk body should either be an Array of commands/string, or a String. However, this doesn't make any sense because the console.log(res) command (From the indexall function under http.get client request) outputs the following:
Bulk content prepared
Response: [ { index: { _index: 'my_index', _type: 'my_type', _id: '1' } },
{ id: '5', name: 'The Name' }, ... },
... 120690 more items ]
The above console output appears to show the array in the correct format.
Question
What does TypeError: Bulk body should either be an Array of commands/string, or a String indicate is wrong with the array I am passing into the client.bulk function?
Notes
My server is currently running Elasticsearch 6.2.4 and Java Development Kit version 10.0.1. Everything works as far as the Elaticsearch server and even my Elaticsearch mappings (I didn't provide the client.indices.putMapping code, however I can if it is needed). I have spent multiple hours reading over every scrap of documentation I could find regarding this TypeError. I couldn't find much in regards to the error being thrown, so I am not sure where else to look for information regarding this error.
Seems a typo in your code.
var indexall = function(**madebulk**, callback) {
client.bulk({
maxRetries: 5,
index: "my_index",
type: "my_type",
body: **makebulk**
Check the madebulk & makebulk.

Accessing JSON object properties directly and log it

I'm trying to access JSON Object properties directly and log it, here is my function :
loadProcesses(filter?){
this._postService.getAllProcess(filter)
.subscribe(
res=> {
this.processListe = res;
// console.log(this.processListe.)
}
,null,
() =>{
console.log("get processes liste" + filter)
});
So this.processListe contain a JSON Object, and my JSON format is like this:
{"Person": {
"id": "A256",
"name": "GET",
"status": "active",
"description": "hardworking, openminded",
...
So it will contains exactly the same things, for example if i want to simply print the label on a console log how can i do it ??
Are you looking for something like this:
function parseObject(obj)
{
for(var key in obj)
{
console.log("key: " + key + ", value: " + obj[key])
if(obj[key] instanceof Object)
{
parseObject(obj[key]);
}
}
}
just call parseObject(res) in the subscribe method.
parse it and access the fields.
var obj = JSON.parse(filter);
obj.Person.id;
//etc
parse it in the .subscribe:
res => this.processListe = res.json();
a better solution is to declare your response with any :
loadProcesses(filter?){
this._postService.getAllProcess(filter)
.subscribe(
(res: any)=> {
this.processListe = res;
// console.log(this.processListe.)
}
,null,
() =>{
console.log("get processes liste" + filter)
});
this way you can access any attirbute in your response

Angular 2: Access object data

In my Angular RC2 app I make an observable HTTP call that returns the following JSON to me from the API:
{
"success":true,
"data":
{
"Type": 1
"Details":{
"Id":"123",
"Name":"test",
"Description":"test"
}
}
}
I map the data like this:
this._myService.get(id)
.subscribe(
(data) => {
this.details = data.Details;
this.type = data.Type;
},
(error) => {
this.setError(error);
}
);
How do I access the values inside the "Details" object from here?
I tried:
{{details.Name}}
But that won't work and I can't use ngFor to loop it either.
You could use the Elvis operator for this:
{{details?.Name}}
As a matter of fact, you load your data asynchronously so details is undefined at the beginning.