0

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);
    },
6
  • Can you try something like this console.log(json.result['prediction'][0].label);? Commented Sep 29, 2018 at 6:24
  • 1
    Can you clarify your question? Also jQuery.parseJSON is deprecated as of version 3.0. Commented Sep 29, 2018 at 6:24
  • What kind of output do you want? Commented Sep 29, 2018 at 6:26
  • Jignesh M. Khatri it doesn't seem to work sadly. Commented Sep 29, 2018 at 6:31
  • aloisdg I am trying to get the label name and probability value... Commented Sep 29, 2018 at 6:32

2 Answers 2

4

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.

source

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.

Sign up to request clarification or add additional context in comments.

Comments

1

using map method to get all the labels

json.result[0].prediction.map((obj)=>{return obj.label})

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.