Nick
Nick

Reputation: 14283

jquery error when trying to parse object

I'm fetching some data from a server, and i have them returned in json as objects.

My ajax request is the following:

$.ajax({
 url: Url,
 dataType: 'json',
 success: function (result) {
            var obj = JSON.parse(result)
            $(".result").text(obj);
           }
})

If i try to use JSON.parse(result), it returns an error: Unexpected token o but on my network tab has the result element correct:

{service: "29”,…}
{service: “33",…}
{service: “45”,…}
{service: “70",…}

If i don't use JSON.parse(result), what i have printed is the following:

[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object]

what am i doing wrong? Thanks

EDIT:

if i use this code here:

$.ajax({
   url: Url,
   dataType: 'json',
   success: function (result) {
                    console.log (result)
                    $(".result").text(result.service);
                    console.debug (result.service);
                }
            })

The first console has the following results:

0: Object
 service: "29"
__proto__: Object
1: Object
 service: "29"
__proto__: Object

but nothing is printed in the div, and the second console is undefined

Upvotes: 0

Views: 34

Answers (1)

Amin Jafari
Amin Jafari

Reputation: 7207

when you're using dataType:"json" you don't need to parse the json object, it is by default parsed and you can use it as an object.

The type of data that you're expecting back from the server. If none is specified, jQuery will try to infer it based on the MIME type of the response (an XML MIME type will yield XML, in 1.4 JSON will yield a JavaScript object, in 1.4 script will execute the script, and anything else will be returned as a string). The available types (and the result passed as the first argument to your success callback)

From jQuery.ajax()

Upvotes: 1

Related Questions