How to read Watson Visual Recognition JSON Respsonse with YAJL Library? - ibm-watson

How do I use the YAJL lib from Scott Klement correctly to read the response of Watson Visual Recognition? The json object looks like this:
{
"images": [
{
"classifiers": [
{
"classifier_id": "default",
"name": "default",
"classes": [
{
"class": "outside mirror",
"score": 0.85,
"type_hierarchy": "/reflector/mirror/outside mirror"
},
{
"class": "mirror",
"score": 0.998
},
{
"class": "reflector",
"score": 0.998
},
{
"class": "car mirror",
"score": 0.764,
"type_hierarchy": "/reflector/mirror/car mirror"
},
{
"class": "rearview mirror",
"score": 0.714,
"type_hierarchy": "/reflector/mirror/rearview mirror"
},
{
"class": "ash grey color",
"score": 0.778
},
{
"class": "bottle green color",
"score": 0.532
}
]
}
],
"source_url": "https://.jpg",
"resolved_url": "https://.jpg"
}
],
"images_processed": 1,
"custom_classes": 0
}
Now I want get the values from the classes objects with class, score_hierarchy.
How can I get to the classes array?
After getting the images object i cannot find the classifiers to continue...
docNode = yajl_stmf_load_tree( temporaryFile: errMsg);
if errMsg <> '';
return imageClasses;
endif;
i = 0;
images = YAJL_OBJECT_FIND(docNode: 'images');
dow yajl_array_loop(images: i: node);
// TODO: How to continue to get "classifiers" object?
j = 0;
dow yajl_object_loop(node:j:key:val);
select;
when key = 'classes';
imageClasses(i).class = yajl_get_string(val);
when key = 'score';
imageClasses(i).score = yajl_get_number(val);
when key = 'type_hierarchy';
imageClasses(i).typeHierarchy = yajl_get_string(val);
endsl;
enddo;
enddo;
yajl_tree_free(docNode);

I believe this should do it:
docNode = yajl_stmf_load_tree( temporaryFile: errMsg);
if errMsg <> '';
return imageClasses;
endif;
i = 0;
images = YAJL_OBJECT_FIND(docNode: 'images');
dow yajl_array_loop(images: i: node);
classifiers = YAJL_OBJECT_FIND(node: 'classifiers');
j = 0;
dow yajl_object_loop(classifiers:j:key:val);
select;
when key = 'classes';
imageClasses(i).class = yajl_get_string(val);
when key = 'score';
imageClasses(i).score = yajl_get_number(val);
when key = 'type_hierarchy';
imageClasses(i).typeHierarchy = yajl_get_string(val);
endsl;
enddo;
enddo;
yajl_tree_free(docNode);
And if you want more examples, this page provides some more:
https://www.fieldexit.com/forum/display?threadid=199

Here's the code that works now:
images = YAJL_OBJECT_FIND(docNode: 'images');
i = 0;
dow yajl_array_loop(images: i: node);
classifiers = YAJL_OBJECT_FIND(node: 'classifiers');
k = 0;
dow yajl_array_loop(classifiers: k: node);
classes = YAJL_OBJECT_FIND(node: 'classes');
j = 0;
dow yajl_array_loop(classes: j: node);
val = YAJL_object_find(node:'class');
imageClasses.classes(j).class = yajl_get_string(val);
val = YAJL_object_find(node:'score');
imageClasses.classes(j).score = yajl_get_number(val);
val = YAJL_object_find(node:'type_hierarchy');
imageClasses.classes(j).typeHierarchy = yajl_get_string(val);
enddo;
enddo;
enddo;

Related

Get the differences between 2 maps flutter

I have 2 maps and I want to get the missing elements as a list. For example:
var map1= [
{"name":"name1","email":"name1#email.com"},
{"name":"name2","email":"name2#email.com"},
{"name":"name3","email":"name3#email.com"},
];
var map2= [
{"name":"name1","email":"name1#email.com"},
{"name":"name2","email":"name2#email.com"},
];
Output: [{"name":"name3","email":"name3#email.com"}]
I tried this approach:
var removedElements = map2.where((element) =>
!map1
.contains(element['email']))
.toList();
but it doesn't work. Any help would be great.
try with this
void main() {
var map1 = [
{"name": "name1", "email": "name1#email.com"},
{"name": "name2", "email": "name2#email.com"},
{"name": "name3", "email": "name3#email.com"},
];
var map2 = [
{"name": "name1", "email": "name1#email.com"},
{"name": "name2", "email": "name2#email.com"},
];
var removedElements = [];
var k;
for (var i in map2) {
for (var j in map1) {
if (i["email"] != j["email"]) {
k = j;
}
}
removedElements.add(k);
}
print(removedElements.toSet().toList());
}
Another approach
var removedElements =
map2.where((element) {
for(var i in map1){
if(i["email"] == element["email"]){
return false;
} else{
return true;
}
}
}).toList();
print(removedElements);
output
: [{name: name3, email: name3#email.com}]

Convert Flat JSON string into hierarchical using Parent ID

I am implementing a Mat-Tree using Angular Material. I have a flat JSON string like:
"Entity": [
{
"ID": 1,
"NAME": "Reports",
"PARENTID": "0",
"ISACTIVE": "Y",
"CREATIONDATE": "2020-03-31T15:08:11",
"UPDATIONDATE": "2020-03-31T15:08:11",
"CREATEDBY": 596241,
"UPDATEDBY": 596241
},
{
"ID": 2,
"NAME": "TMS - Reports",
"PARENTID": 1,
"ISACTIVE": "Y",
"CREATIONDATE": "2020-03-31T15:08:38",
"UPDATIONDATE": "2020-03-31T15:08:38",
"CREATEDBY": 596241,
"UPDATEDBY": 596241
},
{
"ID": 3,
"NAME": "TMS - Beneficiary ",
"PARENTID": 2,
"ISACTIVE": "Y",
"CREATIONDATE": "2020-03-31T15:09:34",
"UPDATIONDATE": "2020-03-31T15:09:34",
"CREATEDBY": 596241,
"UPDATEDBY": 596241
}
]
And I need to convert it into Key-value pairs based on their Parent ID. Something like:
{
Reports:
{
'Type 1 Reports': ['Beneficiary Reports', 'Some Other Report'],
'Type 2 Reports': null //No Children,
},
Some Other Menu Items: {
'My Parent Node': null,
'Some Other Menu Node': ['Child 1', 'Child 2']
}
}
So far, I am able to use this code to convert it into a parent-child hierarchy, but It has pushed all children into Items array which I cannot iterate with Mat-Tree. I need to get rid of the Items and have something like a key-value pair as the one I mentioned above:
generateTreeData(menuResponse)
{
var map = {};
for(var i = 0; i < menuResponse.length; i++){
var obj = menuResponse[i];
var parent = '';
obj.items= [];
map[obj.ID] = obj;
if(obj.PARENTID == "0")
{
parent = '-';
}
else
{
parent = obj.PARENTID;
}
if(!map[parent]){
//Means Parent doesnt exist i.e. node Itself is parent node
map[parent] = {
items: []
};
}
map[parent].items.push(obj);
}
return map['-'].items;
}
Problem:
The code puts children nodes in Items array. I need to get rid of the Items array and place it in key-value pairs like the one I mentioned above. How do I just extract the "NAME" and Items out of this JSON array and make a Key-Value pair? Something like the one I mentioned above?
The expected output structure doesn't seem right. What if there is a child for 'Beneficiary Reports' node.
The output structure for the input provided in the question should be like:
{
"Reports":[
{
"TMS - Reports":[
{
"TMS - Beneficiary ":[]
}
]
}
]
}
Check the following fiddle: https://jsfiddle.net/abby_7700/apkgeo1d/3/
var data = [];//your response goes here
var result = {};
var root = data.find(x => x.PARENTID == 0);
result[root.NAME] = [];
findAndAddChildren(root.ID, result[root.NAME]);
console.log(JSON.stringify(result));
function findAndAddChildren(parentID, collection) {
var rootChildren = data.filter(x => x.PARENTID == parentID);
for(var i = 0; i < rootChildren.length; i++) {
var child = rootChildren[i];
var temp = {};
temp[child.NAME] = [];
collection.push(temp);
findAndAddChildren(child.ID, temp[child.NAME]);
}
}

Get the existing intersections between multiple object arrays

I have a couple of arrays which have some same ids. What I want to achieve is get the intersections between the arrays in plain javascript, no libraries. If there is a match of Ids and arraypicklist values are not equal between 2 or more arrays I should get an array with the matching Ids.
Below is my example which I tried but this ends up with no ids where I expect at least 1 match. In this case Id:123 as in the first and second array there is a match. So I would expect
intersection = [{"Id":"123","arrayPicklist":"Categorie__c"},{"Id":"123","arrayPicklist":"Regio__c"}];
fiddle:https://jsfiddle.net/ozckc0tw/4/
var buckets = [[{"Id":"123","arrayPicklist":"Categorie__c"}],
[{"Id":"123","arrayPicklist":"Regio__c"}],
[{"Id":"124","arrayPicklist":"Categorie__c"}],
[{"Id":"123","arrayPicklist":"Regio__c"},{"Id":"125","arrayPicklist":"Regio__c"},{"Id":"123","arrayPicklist":
"Regio__c"},{"Id":"126","arrayPicklist":"Regio__c"}]]
function IntersectionByKey(key) {
var i,
j,
k,
ret = [],
item,
args = [].slice.call(arguments, 1);
args.sort(function(a, b) {return a.length - b.length});
i:for(i=0; i<args[0].length; i++) {
item = [Object.assign(args[0][i], {})];
j:for(j=1; j<args.length; j++) {
for(k=0; k<args[j].length; k++) {
if(key in args[0][i] && args[0][i][key] == args[j][k][key]){
item.push(Object.assign(args[j][k], {}));
continue j;
}
}
continue i;
}
ret.push(item);
}
return ret;
}
var key = 'Id';
var intersection = IntersectionByKey.apply(null, [key].concat(buckets));
console.log('intersection '+JSON.stringify(intersection))
Done,Sorry, but I did not looked out your code, I tried my logic with your requirements, You can use it.
my logic
var buckets = [
[{
"Id": "123",
"arrayPicklist": "Categorie__c"
}],
[{
"Id": "123",
"arrayPicklist": "Regio__c"
}],
[{
"Id": "124",
"arrayPicklist": "Categorie__c"
}],
[{
"Id": "123",
"arrayPicklist": "Regio__c"
}, {
"Id": "125",
"arrayPicklist": "Regio__c"
}, {
"Id": "123",
"arrayPicklist": "Regio__c"
}, {
"Id": "126",
"arrayPicklist": "Regio__c"
}]
],
intersection = [{
"Id": "123",
"arrayPicklist": "Categorie__c"
}, {
"Id": "123",
"arrayPicklist": "Regio__c"
}];
var resArray = [];
for (var j = 0; j < intersection.length; j++) {
for (var i = 0; i < buckets.length; i++) {
for (var k = 0; k < buckets[i].length; k++) {
if (buckets[i][k].Id == intersection[j].Id && buckets[i][k].arrayPicklist == intersection[j].arrayPicklist) {
resArray.push(buckets[i][k]);
}
}
}
}
console.log(resArray);

Convert JSON.STRINGIFY to json array length is not calculating

Hi i have excel upload functionality when i upload the excel that should save in to the mongodb(database). I have taken the excel cell value as json stringify and also i converted that as parse. now i don't how to get that json length value.
here i have attached my code
function to_json(workbook) {
debugger;
console.log(workbook);
var result = {};
workbook.SheetNames.forEach(function(sheetName) {
$scope.Sheetname=sheetName; // here sheet name is excel sheet name
MainSheetName=sheetName;
var roa = X.utils.sheet_to_json(workbook.Sheets[sheetName]);
if(roa.length > 0){
result[sheetName] = roa;
}
});
return result;
}
var HTMLOUT = document.getElementById('htmlout');
function to_html(workbook) {
HTMLOUT.innerHTML = "";
workbook.SheetNames.forEach(function(sheetName) {
var htmlstr = X.write(workbook, {sheet:sheetName, type:'binary', bookType:'html'});
HTMLOUT.innerHTML += htmlstr;
});
}
var tarea = document.getElementById('b64data');
function b64it() {
if(typeof console !== 'undefined') console.log("onload", new Date());
var wb = X.read(tarea.value, {type: 'base64',WTF:wtf_mode});
process_wb(wb);
}
window.b64it = b64it;
var OUT = document.getElementById('out');
var global_wb;
function process_wb(wb) {
global_wb = wb;
var output = "";
var output1 = "";
switch(get_radio_value("format")) {
case "json":
output = JSON.stringify(to_json(wb), 2, 2);
output1=JSON.parse(output);
break;
case "form":
output = to_formulae(wb);
break;
case "html": return to_html(wb);
default:
output = to_csv(wb);
}
if(OUT.innerText === undefined) OUT.textContent = output;
else OUT.innerText = output;
debugger;
$scope.MainInfo=output1; // this return whole data
console.log(output1);
$scope.jsondata=output1.Sheet1[0].length;// this returns undefined. Here sheet name is excel file sheetName it will taken from excel.
console.log($scope.jsondata);
my output is showing like this
{
"Sheet1": [
{
"Name": "xxx",
"Age": "22",
"Salary": "222222"
},
{
"Name": "yyy",
"Age": "23",
"Salary": "232323"
},
{
"Name": "zzz",
"Age": "23",
"Salary": "232323"
}
]
}
now i want length of Sheet1 how can i get that. can any one tell me
If you were to assign your output to obj getting the length of Sheet1 would be as simple as going obj.Sheet1.length
Try this :
var output = {
"Sheet1": [{
"Name": "xxx",
"Age": "22",
"Salary": "222222"
}, {
"Name": "yyy",
"Age": "23",
"Salary": "232323"
}, {
"Name": "zzz",
"Age": "23",
"Salary": "232323"
}]
};
var newArr = $.grep(output1.Sheet1, function( value, index ) {
if(n.Name == "xxx") {
return n;
}
});
console.log(newArr)
You can use angular.fromJson(yourJson).length functionality.
In your case, it should be angular.fromJson($scope.jsondata).length.
As per my understanding from above code, your are getting response into JSON string format so you can't perform JSON operation over it. try to convert json string to json object using JSON.parse method.Below is sample code in node js.
var parseData = JSON.parse(output1);
var parsedata1 = parseData.Sheet1;
for(var namevalue=0;namevalue<parsedata.length;namevalue++){
console.log("Name value: "+parsedata1[namevalue].Name);
}

pushing values from json into array

JSON:
var res =
{
"response": {
"data": {
"profilesearchsnippet": [
[
{
"profileInfo": {
"firstname": "Sundar",
"lastname": "v",
"gender": "male",
"country": "Afghanistan",
"state": "Badakhshan",
"city": "Eshkashem",
"pincode": "",
"plancode": "T001",
"userid": 13
},
"roleInfo": {
"defaultphotoid": 94
}
}
],
[
{
"profileInfo": {
"firstname": "ghg",
"lastname": "vbhvh",
"gender": "male",
"state": "Badakhshan",
"city": "Eshkashem",
"pincode": "454",
"plancode": "T001",
"userid": 22
},
"roleInfo": {
"defaultphotoid": 171
}
}
]
]
}
}
}
In the above json , I need to move roleInfo.defaultphotoid into var image
JS:
$scope.setimage = res.response.data.profilesearchsnippet[0];
for (var i = 0; i++; i<setimage.length; i++){
var image = [];
image .push(setimage[i].roleinfo.defaultphotoid);
}
I assigned one variable named setimage and from there I am trying to push values of all defaultphotoid in another array image to fetch images of all roleinfos, but I am able to fetch only first value.
This is because var image = [] is inside the for loop. It gets re-initialized after every cycle. You need to put it outside the loop
$scope.setimage = res.response.data.profilesearchsnippet[0];
var image = [];
for (var i = 0; i<$scope.setimage.length; i++){
image.push($scope.setimage[i].roleinfo.defaultphotoid);
}
You could use angular.foreach inorder to iterate the elements and set into the variable.
var log = [];
angular.forEach(res.response.data.profilesearchsnippet[0], function(value, key) {
this.push(setimage[i].roleinfo.defaultphotoid);
}, log);
https://docs.angularjs.org/api/ng/function/angular.forEach
try this:
$scope.setimage = res.response.data.profilesearchsnippet;
var images = [];
for (var i = 0; i<$scope.setimage.length; i++){
image.push($scope.setimage[i][0].roleinfo.defaultphotoid);
}
will work.

Resources