0

This is a basic javascript question about accessing rows and fields in a variable reference that has json data in it.

I have been told that I need to access the data out of a json string but I am not having any luck...my two alerts are blank...

Here is the code I am testing with:

<body>
<script>

var data = '[ {"comp_id": "190753","comp_name": "ABC Limited"},{"comp_id": "343838","comp_name": "Adams Company"} ]';

// how many rows?

alert(data.rows);   

// the comp_name field on the first record?
alert(data[0].comp_name); 

</script>
</body>

Please help.

Thx Scott

  • 1
    See my answer here: http://stackoverflow.com/questions/23310353/how-to-read-json-result-in-jquery/23310376#23310376 – toesslab May 22 '14 at 19:06

1 Answers1

4

You variable is not a Json, it is a String. You need to parse your variable to Json

Using JQuery for example;

var data = $.parseJSON('[ {"comp_id": "190753","comp_name": "ABC Limited"},{"comp_id": "343838","comp_name": "Adams Company"} ]');

alert(data[0].comp_name);

or JSON.parse

var data = JSON.parse('[ {"comp_id": "190753","comp_name": "ABC Limited"},{"comp_id": "343838","comp_name": "Adams Company"} ]');

alert(data[0].comp_name);
Samuel
  • 1,149
  • 8
  • 25