I tried to use jQuery to do jQuery.parseJSON and JSON.stringify to take a JSON response and I can't seem to get data that is named as label.
{
"message":"Success",
"result":
[
{
"prediction":
[
{
"label":"Anta",
"probability":0.095694885
},
{
"label":"Mice",
"probability":0.9043051
}
]
}
]
}
I'm trying to use ajax to take the request and try to use it as so:
function success(name) {
var json = jQuery.parseJSON(name);
var jsons = JSON.stringify(name);
console.log(json.result['prediction'].label);
},
You can access an array by using an index for example 0 for the first item:
function success(name) {
var json = jQuery.parseJSON(name);
var jsons = JSON.stringify(name);
console.log(json.result[0].prediction[0].label); // == Anta
}
Also JavaScript can parse JSON directly. You should be able to do:
function success(name) {
var json = JSON.parse(name);
console.log(json.result[0].prediction[0].label); // == Anta
}
By the way, you can read in the jquery doc:
As of jQuery 3.0, $.parseJSON is deprecated. To parse JSON strings use the native JSON.parse method instead.
If you want to get all labels:
function success(name) {
const json = JSON.parse(name);
const labels = json.result.map(r => r.prediction.map(p => p.label)).flat().flat();
console.log(labels); // == Anta, Mice
}
This is a es6 solution using map()
and flat()
. Check their doc on msdn in case of doubt.
using map method to get all the labels
json.result[0].prediction.map((obj)=>{return obj.label})