Search code examples
javascripthtmlarraysjsongetjson

Can't access an element in JSON array


No one really answered this question but how on earth can one use this JSON return data from a php/mysql direct using JavaScript?

Here is the return data once i used JSON.parse and saved it to the Javascript variable obj

[{"stuid":"10-00002","stuname":"Meratis, Velino","stucourse":"Arts","stustat":"0","stulyear":"4","stulog":"feb 16 2017"},{"stuid":"10-00003","stuname":"Melker, Alana","stucourse":"Wilderness","stustat":"1","stulyear":"5","stulog":"feb 16 2017"}]

I've tried the simple obj.stuname but it returns only an undefined i've tried many times to understand it but i can't seem to use this array at all. Could anyone help on this?

I've also tried the reObj = {"stu":obj}; style but then it only returns an [object Object]

so please someone elaborate on this?


Solution

  • obj is a json array, so you have to access an element using its index.

    Also, you have to use JSON.parse in order to turn a string of json text to a Javascript object.

    Try this:

    var stuname=obj[0].stuname;
    

    var obj='[{"stuid":"10-00002","stuname":"Meratis, Velino","stucourse":"Arts","stustat":"0","stulyear":"4","stulog":"feb 16 2017"},{"stuid":"10-00003","stuname":"Melker, Alana","stucourse":"Wilderness","stustat":"1","stulyear":"5","stulog":"feb 16 2017"}]';
    var objParsed=JSON.parse(obj);
    console.log(objParsed[0].stuname);

    If you want to iterate array, use forEach method.

    var obj='[{"stuid":"10-00002","stuname":"Meratis, Velino","stucourse":"Arts","stustat":"0","stulyear":"4","stulog":"feb 16 2017"},{"stuid":"10-00003","stuname":"Melker, Alana","stucourse":"Wilderness","stustat":"1","stulyear":"5","stulog":"feb 16 2017"}]';
    var objParsed=JSON.parse(obj);
    objParsed.forEach(function(item){
      console.log(item.stuname);
    });