William James Kasurak
William James Kasurak

Reputation: 11

save parsed JSON as obj

first question ever, I'm trying to parse a JSON file stored within the same file directory on my webhost as my html file that runs the javascript to parse it, I've added a console.log to debug and confrim that the file is being caught by the 'get' to ensure that I am able to 'get' the file throgh the use of jquery getJSON, in the callback i've tried to create a function that re-defines a global variable as an object containing the parsed data, but when I try to inject it into a document.getElemendtById('example').innerhtml = tgmindex.ToughGuys[1].name;

it returns a error "Uncaught TypeError: Cannot read property '1' of undefined"

here's my js/jquery

var tgmIndex;
$(document).ready(function () {
$.getJSON("http://webspace.ocad.ca/~wk12ml/test.json",function(data){  
    console.log( "success" );
    
tgmIndex =$.parseJSON;   
    
document.getElementById('tgm1').innerHTML= tgmIndex.ToughGuys[1].name; 
});
});

and here is whats contained in the JSON (i made sure to try linting it first and it's a valid json)

{"ToughGuys":[ {"name":"Ivan", "position":"Executive"}, {"name":"Little Johnny", "position":"Intern"}, {"name":"Beige Cathy", "position":"Executive"}, {"name":"Stan", "position":" original Intern"} ]}

Upvotes: 0

Views: 50

Answers (2)

Shaun
Shaun

Reputation: 3895

Presumably your service is returning application/json. Therefore data already contains the json.

tgmIndex = data;

Then... "Tough Guys" is what you should be indexing. Not "ToughGuys"

Your example JSON is wrong in your question. If I go to

http://webspace.ocad.ca/~wk12ml/test.json

I see:

{"Tough Guys":[
    {"name":"Ivan", "position":"Executive"},
    {"name":"Little Johnny", "position":"Intern"},
    {"name":"Beige Cathy", "position":"Executive"},
    {"name":"Stan", "position":"Intern 0"}
]}

See "Tough Guys" There's your problem.

document.getElementById('tgm1').innerHTML= tgmIndex['Tough Guys'][1].name;

If data for some reason isn't JSON:

tgmIndex = $.parseJSON(data);

Upvotes: 0

Crob
Crob

Reputation: 15185

You're setting tgmIndex to the parseJson function.

Should be doing tgmIndex =$.parseJSON(data);

Upvotes: 1

Related Questions