0

I have created a JSON like this one :

{"data":[{"content":"Event1","start":"new Date(2014,07,10)"},{"content":"Event2","start":"new Date(2014,07,17)"}],"success":true}

In order to fit the following code in Javascript :

 data = [
          {
             'start': new Date(2010,7,23),
             'content': 'Event'
          },
          {
             'start': new Date(2010,7,23),
             'content': 'Event'
          },
];

Witth th JSON i have, i can easily access field, for example :

json.data[0].content 

Return : "Event1"

My question is : how can i make the Javascript code "dynamic" to load every components in my JSON, assuming the fact that i don't know how many elements it will contains ?

Currently, i've done the followig code :

var xhr = new XMLHttpRequest(); 
xhr.open("GET", "/Test", true); // Call to a java servlet 
xhr.send();  

var json;
var jsonLength; 
var data; 

xhr.onreadystatechange = function(){
  if(xhr.readyState == 4 && xhr.status == 200){
    json = JSON.parse(xhr.responseText);
    jsonLength = json.data.length; 
  }
}

 data = [];

 for(var i = 0 ; i < jsonLength ; i++){
    data.push({
       'start':json.data[i]['start'],
       'content':json.data[i]['content']
     })
 }

timeline.draw(data);

EDIT : I don't even enter to the for loop ... Why ?

Mornor
  • 3,471
  • 8
  • 31
  • 69

4 Answers4

3

That's quite simple as these are just arrays and hash objects in JavaScript.

So you can just iterate over them:

for(var i = 0; i < json.data.length; i++) {
  var item = data[i];
  // Insert this into your data table
  // Here you can use item which is set to the current item you are iterating over
}

JavaScript even let's you inspect your so you can look at the individual data item and find out what properties it has like this (see this question for details):

var keys = [];
for(var k in obj) keys.push(k);

UPDATE:

It seems you have fallen into the asynchrosity trap that JavaScript lays out. The function xhr.onreadystatechange is only called once the event happens, the code below that function is executed instantly. So you where iterating over an empty dataset since the data you where looking at was not yet loaded.

JavaScript is very much callback based and especially with AJAX. Always keep in mind when the code will run, in this case xhr.onreadystatechange = function returns instantly and the code after continues to run. Only inside the function can you expect your variables to be set correctly.

var xhr = new XMLHttpRequest(); 
xhr.open("GET", "/Test", true); // Call to a java servlet 
xhr.send();  

var json;
var jsonLength; 
var data; 

xhr.onreadystatechange = function(){
  if(xhr.readyState == 4 && xhr.status == 200){
    json = JSON.parse(xhr.responseText);
    jsonLength = json.data.length; 


    data = [];

    for(var i = 0 ; i < jsonLength ; i++){
       data.push({
          'start':json.data[i]['start'],
          'content':json.data[i]['content']
       })
    }

    timeline.draw(data);

  }
}
Community
  • 1
  • 1
Tigraine
  • 23,358
  • 11
  • 65
  • 110
  • So i will have in my loop : var item = data[i] ; data = [ {'start':'item.start', 'content':'item.content'}] ? – Mornor Jul 23 '14 at 09:10
  • Almost correct - as you can see I assign the data item at the position i (the loop variable) to the variable `item` so in this case item would be { 'start': '2014-07-23 11:37', content: 'Event' } .. and on the next iteration of the loop it would contain the next values – Tigraine Jul 23 '14 at 09:37
  • I think i'm close ... I wrote that in a loop, but does not work : data.push({ 'start':json.data[i].start, 'content':json.data[i].content }) Any idea ? – Mornor Jul 23 '14 at 11:31
  • I don't think you should push into the same array you are pulling data from.. please edit your question and explain what you are trying to do exactly so we might be able to help you in more detail – Tigraine Jul 23 '14 at 11:38
1

If your json is a string, just do

obj = JSON.parse(jsonString);

Then you'll have an object containing your json data, where you can access using obj[0].content (as an example)

Else, just iterate throught the json object, like Tigraine said.

(You question is a little bit unclear though)

Larta
  • 406
  • 2
  • 9
0

try this:

var x={"data":[{"content":"Event1","start":"new Date(2014,07,10)"},{"content":"Event2","start":"new Date(2014,07,17)"}],"success":true};

for(i=0;i<x.data.length;i++)
    {
     console.log("content: "+x.data[i].content+" start: "+ x.data[i].start);
    }
Super Hornet
  • 2,839
  • 5
  • 27
  • 55
0
    <script type="text/javascript">
        var json = {
            'data': [
                {
                    'start': new Date(2010, 7, 23),
                    'content': 'Event'
                },
                {
                    'start': new Date(2010, 7, 23),
                    'content': 'Event'
                },
            ]
        };
        alert(json['data'].length);
        $(function() {
        });
    </script>
Salathiel Genese
  • 1,639
  • 2
  • 21
  • 37