user3872094
user3872094

Reputation: 3351

Confusing result with json conversion

I'm writing a code where there is a REST call made and the result is sent back.

Using the below js code (Ajax/jQuery), I'm pulling the data.

success : function(msg) {
            dataObj = msg;
            var jsonResp = JSON.stringify(dataObj);

            alert(dataObj.answer + "\t" + dataObj);
            console.log(dataObj.answer + "\t"+ dataObj);
            document.getElementById('time').innerHTML = dataObj;
        }

The console output that I get is

undefined   {"answer":"Hello","score":"100"}

instead of

Hello   {"answer":"Hello","score":"100"}

please let me know where am I going wrong and how can I fix this.

Thanks

Upvotes: 0

Views: 43

Answers (1)

Barmar
Barmar

Reputation: 781059

dataObj = msg;

should be

dataObj = JSON.parse(msg);

or you can use the dataType: 'json' option to $.ajax() so that jQuery will do this automatically.

Upvotes: 1

Related Questions