0

My AJAX result is

["1","O"]

I'm trying to access 1, but

console.log(result[0]);

gives me

'['

How can I make it as an object and get just the first element of my array result?

  • You may want to consider Douglas Crockford's [json2.js](https://github.com/douglascrockford/JSON-js/blob/master/json2.js) to ensure compatability of `JSON.parse` across browsers. – Jared Farrish Apr 25 '14 at 22:16

2 Answers2

2

It looks like you are indexing into the string of your result. Try

var resultObj = JSON.parse(result);
console.log(resultsObj[0]);
Joel Jeske
  • 1,618
  • 14
  • 17
  • So I was trying result = $.parse(result); dont we have such a thing? If yes, what is the difference! –  Apr 25 '14 at 22:10
  • 1
    There is a jQuery.parseJSON() but not a simple parse. https://api.jquery.com/jQuery.parseJSON/ Using jQuery provides more robustness as it will use JSON if available and otherwise try eval. http://stackoverflow.com/questions/10362277/jquery-parsejson-vs-json-parse – Joel Jeske Apr 25 '14 at 22:11
1

What you're accessing is the string of the result. You need to parse it out of JSON format.

result = JSON.parse(result);
Mike Cluck
  • 31,869
  • 13
  • 80
  • 91
  • So I was trying result = $.parse(result);and not working! dont we have such a thing? If yes, what is the difference! –  Apr 25 '14 at 22:12
  • 1
    As Joel said, there isn't a $.parse function. Just use `JSON.parse`. – Mike Cluck Apr 25 '14 at 22:12