user2900150
user2900150

Reputation: 441

How can I parse this JSON Object in javascript?

Looking for some guidance here on how can I extract Alok,Test and Test2

Object {value: "{"actors":["Alok","Test","Test2"]}"}

I have almost spent entire day to figure out the way to parse this JSON array but closest I reached is getting all characters printed in a single line.

My javascript implementation is:

        AJS.$.ajax({
            dataType: 'json',
            type: 'GET',
            url: AJS.params.baseURL+"/rest/leangearsrestresource/1.0/message/list/{actor}",
            async: false,
            multiple: true
        }).done(function(result) {
                    AJS.log(result);
                    //var obj = JSON.parse(result);
                    //AJS.log(obj.actors[1]);

            //AJS.log("Actor is " + result.length);
            var output = '';
            for(var key in result) {
                AJS.log("Key: " + key + " value: " + result[key]);
                var myThing = result[key];
                var output = myThing.property
                AJS.log(output)
               // AJS.log(output.text)
                for( thingKey in myThing ) {

                    AJS.log(myThing[thingKey])
                }

            }

Also attaching the console screenshotenter image description here

Upvotes: 0

Views: 444

Answers (4)

Paolo
Paolo

Reputation: 15827

You're getting a json data that, when parsed, results in a object with a key named "value" and its pair value that is another json string.

So you have to get that string and parse it again.

Then you can access it as a JavaScript object.

This is the done callback rewritten:

function( result ) {
    var json,
        obj,
        actors;

    json = result.value;
    obj = JSON.parse( json );
    actors = obj.actors;

    for( idx in actors ) {
        AJS.log( actors[ idx ] );
    }
}  

Upvotes: 1

borja gómez
borja gómez

Reputation: 1051

The result object is not fully parsed it has a property value which contains a string so you have to parse the value of value property like this: JSON.parse(result.value) and you will get an object with one property "actors" whose value is an array with the strings "Alok","Test","Test2".

Upvotes: 1

Kram
Kram

Reputation: 526

If you are sure that you have a valid JSON, use this: jQuery.parseJSON(str)

Upvotes: -1

som
som

Reputation: 4656

for( thingKey in myThing.actors ) {

    AJS.log(myThing[thingKey])
}

You need to modify your code. Because the index is actors. actors is a array. So you can iterate array in for loop.

Upvotes: 0

Related Questions