Object.length = undefined

Hi!

I'm new to programming in java, and wonder why this code returns the length of object as undefined..

(Seems like the posting editor screws up the url below...)[fixed]

var names;

function preload() {
    var url = "https://" + "raw.githubusercontent.com/dominictarr/random-name/master/first-names.json"
    names = loadJSON(url);
}


function setup() {
    noCanvas();
    createP("Total amount of names loaded from web is: " + names.length)
}


function draw() {
}
Tagged:

Answers

  • I'm new to programming in java

    that's javascript, not java.

    typically you aren't allowed to load data from a different website.

    check the browser console for errors.

  • I'm sorry, in Javascript.. Well, the page manage to load the data.. (See picture) names_fail

    It means that the names are loaded, but still the object? have no length..

    Regards Mike

  • try just print(names);

    i'm wondering whether .length is wrong

    and what is createP?

  • edited February 2017

    You can't get the length from json. You first need to parse your data into an array. Here's some working code, I've simply looped through the json and pushed it into an array I named "names":

    var data;
    var names = [];
    
    function preload() {
        var url = "https://" + "raw.githubusercontent.com/dominictarr/random-name/master/first-names.json";
        data = loadJSON(url);
    
    }
    
    function setup() {
        noCanvas();
        for (x in data) {
          names.push(data[x]);
        }
        createP("Total amount of names loaded from web is: " + names.length);
    }
    
    function draw() {
    }
    
Sign In or Register to comment.