1

I have ajax code which returns JSON data which is just Array of string(no key/val pair).

function loadData() {
    $.ajax({
    type: 'GET',
    url: apiURL,
    dataType: "json",
    timeout: 2000,
    success: onLoadData
};

function onLoadData(data) {
    console.log(data);
    var arr = JSON.parse(data);
    //var arr = jQuery.parseJSON(data); this also fails.
    alert(arr[0]);
};

Output of console.log() is = ["one", "two", "three"] but JSON.parse() gives error as :

Uncaught SyntaxError: Unexpected token o

I checked JSON using validator which says this is valid JSON. Can someone help to understand why parse() is failing?

2
  • 3
    It's an array already, you cannot JSON.parse() an array. If you specify dataType: "json" jquery parses it for you. Commented Dec 17, 2014 at 20:25
  • Setting your dataType to json automatically parses the response as json Commented Dec 17, 2014 at 20:25

2 Answers 2

4

Just remove JSON.parse(data) if its already an array. You'll see that your alert call should work fine.

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

2 Comments

The reason WHY this works is in the documentation of jQuery's ajax. The function gets passed three arguments: The data returned from the server, formatted according to the dataType parameter.... The dataType states 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,.... So jQuery by default usually decodes a JSON string into a Javascript Object.
thanks @ErikPhilips for details. Yes I found that parse() needs developer.mozilla.org/en/docs/Web/JavaScript/Reference/… parameter of type string and because typeof(data) is object, using var string_data = JSON.stringify(data); solves the issue so as said in above answers "data" is alerady array it need not to parse.
0

Just do:

alert(data[0]) // and remove everything else in that callback. 

You're already fine with that dataType : "json".

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.