Search code examples
javascriptjsoncasperjs

How do I load JSON file in CasperJS script to loop through?


I need to load the JSON file and iterate through it in a loop. Here is the json

test.json:

[
    ["AA", "1112223333"],
    ["AM", "2223334444"],
    ["BF", "3334445555"],
    ["CP", "4445556666"],
    ["JB", "5556667777"],
    ["TC", "6667778888"],
    ["TT", "7778889999"]
]

The Casper script:

var casper = require('casper').create({
    logLevel: 'debug'

});

var json = require('test.json');
console.log(json);
require('utils').dump(json);

ultimately I see it loading as an array just like the file essentially. Then I will loop through the variable and use the initial and phone number in the script.


Solution

  • You can try "each" function (here)

    Here is an example code.

    var casper = require('casper').create({
        logLevel: 'debug'
    });
    var json = require('test.json');
    casper.start().each(json, function(self, item, index) {
        this.echo(item[1]);
        // Also you can use index to filter the items inside array.
    }).run();