0

I'm trying to retrieve data from a source in JSON. I am able to retrieve some of the data such as "episode_name" & "overview", however I'm having issues with some data such as "writers" & "directer".

This is the code i'm using along with my example

   var jsontext = '{"first_aired":"2004-06-06","episode_name":"Let Em Eat Cake","overview":"Blahh Blahh","writers":[{"name":"Jim Vallely"},{"name":"Mitchell Hurwitz"}],"directors":[{"name":"Paul Feig"}],"guest_stars":[{"name":"Ian Roberts"},{"name":"Judy Greer"},{"name":"Stacey Grenrock-Woods"},{"name":"Matt Walsh"},{"name":"Alessandra Toreson"}]}';
    var titles = JSON.parse(jsontext);
    document.write(titles.episode_name);

Basically the problem comes down to not being able to retrieve data on a multilevel basis. I'm not sure how to do this.

Here is my example in JS Fiddle for editing it to show me. http://jsfiddle.net/k3V9p/1/

Thank You

Craig
  • 133
  • 1
  • 13
  • possible duplicate of [Access / process (nested) objects, arrays or JSON](http://stackoverflow.com/questions/11922383/access-process-nested-objects-arrays-or-json) – Felix Kling Nov 28 '13 at 19:46

2 Answers2

1

The writers subobject is an array, so you would access its elements and subobjects like so:

titles.writers[0].name
Jim Cote
  • 1,746
  • 3
  • 15
  • 26
  • And if the lists are really just arrays of names, you don't even have to make them arrays of objects. Just make them arrays of strings. – Jim Cote Nov 28 '13 at 19:46
0

You can collect the writer´s names with a loop

    var jsontext = '{"first_aired":"2004-06-06","episode_name":"Let Em Eat Cake","overview":"Blahh Blahh","writers":[{"name":"Jim Vallely"},{"name":"Mitchell Hurwitz"}],"directors":[{"name":"Paul Feig"}],"guest_stars":[{"name":"Ian Roberts"},{"name":"Judy Greer"},{"name":"Stacey Grenrock-Woods"},{"name":"Matt Walsh"},{"name":"Alessandra Toreson"}]}';
    var titles = JSON.parse(jsontext);
    var names = [];
    $.each(titles.writers, function(i,it){
      names.push(it.name);
    })
    alert(names);

http://jsfiddle.net/k3V9p/2/

john Smith
  • 17,409
  • 11
  • 76
  • 117