Search code examples
javascriptjsoncasperjs

How to get a JSON in CasperJS?


I have some arguments name1, name2, name3. How can I get a JSON file containing these arguments? I try do this, but I get nothing:

var jsonStr = this.evaluate(function(){
       var outjson = {};
       var outjson = {'name1': name1, 'name2': name2, 'name3': name3};
       return JSON.stringify(outjson);
       });
    fs.write('myFile.json', jsonStr, 'w');

Solution

  • There is no closure for the function, you evaluate. You can read something about it here: http://phantomjs.org/api/webpage/method/evaluate.html

    That's why the variables name1, name2 and name3 are undefined, when you evaluate the function.

    Phantom 2 has the following bug in current releases - an error in a function being evaluate rises no exception. In such a case the evaluate simply returns null.

    So, you have an error in you function being evaluate and get nothing.

    You can try the following example, which prints

    jsonStr: {"name1":1,"name2":2,"name3":3}

    var casper = require('casper').create();
    var fs = require('fs');
    
    casper.start('http://casperjs.org/', function() {});
    
    casper.then(function() {
        var jsonStr = this.evaluate(function() {
            var outJson = {'name1': 1, 'name2': 2, 'name3': 3};
            return JSON.stringify(outJson);
        });
    
        this.echo('jsonStr: ' + jsonStr);
    
        fs.write('myFile.json', jsonStr, 'w');
    
    });
    
    casper.run();
    

    and the following example, which prints

    jsonStr: null

    var casper = require('casper').create();
    
    casper.start('http://casperjs.org/', function() {});
    
    casper.then(function() {
        var jsonStr = this.evaluate(function() {
            var outJson = {'name1': name1, 'name2': name2, 'name3': name3};
            return JSON.stringify(outJson);
        });
    
        this.echo('jsonStr: ' + jsonStr);
    });
    
    casper.run();