P.Brian.Mackey
P.Brian.Mackey

Reputation: 44275

Reading a JSON object

I have a Service which returns JSON using C#'s JavaScriptSerializer class.

jQuery

        $.get('GlobalService/Index',
            { crudOperation: crudOperation,
                globalType: globalType,
                globalObject: globalObject
            },
            function (data) {
                alert(data);
            });

the callback function displays in the alert

[object XMLDocument]

How do I get to and parse the JSON object? The object has basic construction

{"field1":"data","field2":"more data",/*...~10 more of these*/}

Upvotes: 0

Views: 630

Answers (4)

Diosney
Diosney

Reputation: 10580

You must specify a dataType of "json" in order to let the method know how parse the returned data:

      $.get('GlobalService/Index',
            { crudOperation: crudOperation,
                globalType: globalType,
                globalObject: globalObject
            },
            function (data) {
                alert(data);
            }, 'json');

See $.get() documentation at jQuery: http://api.jquery.com/jQuery.get/.

Note that if you don't specify dataType, jQuery will do a smart guess of what the server is returning and it is very clear that it is misunderstanding the server response with an XML block of code.

Upvotes: 1

Shef
Shef

Reputation: 45589

$.get('GlobalService/Index',
{ 
    crudOperation: crudOperation,
    globalType: globalType,
    globalObject: globalObject
},
function (data) {
    // access it as you would normally access a JS object
    alert(data.field1);
}, 
'json'); // do not forget to pass the json data type here, otherwise it 
         // will just guess it (probably wrong, as it shows in your case)

Upvotes: 3

Naftali
Naftali

Reputation: 146302

Your code is working fine, just an alert cannot show the object data:

    $.get('GlobalService/Index',
        { crudOperation: crudOperation,
            globalType: globalType,
            globalObject: globalObject
        },
        function (data) {
            console.log(data); //view data in console
            alert(data.field1);
        });

Upvotes: 2

Andrew
Andrew

Reputation: 13853

Easiest way. @see getJSON

also,

parseJSON

Upvotes: 2

Related Questions