简体   繁体   English

CasperJs从本地文件加载json数据

[英]CasperJs loads json data from a local file

Is there any convenient way to load a local JSON file into a variable with CasperJs? 有没有方便的方法将本地JSON文件加载到CasperJs的变量中?

I saw someone suggest to use 我看到有人建议使用

$.getJSON(filename, function() ... 

I have the following working on CasperJS 1.1-beta1 and PhantomJS 1.9.1 我有以下工作在CasperJS 1.1-beta1和PhantomJS 1.9.1

test.json test.json

{
    "test": "hello"
}

test.js test.js

var json = require('test.json');
require('utils').dump(json);
casper.echo(json.test); // "hello"

The solution proposed by @hexid worked for me with one change, i added a './' before the file address to denote it is a local file. @hexid提出的解决方案为我工作了一次更改,我在文件地址前添加了一个'./'来表示它是一个本地文件。

test.json test.json

{
    "test": "hello"
}

test.js test.js

var utils = require('utils');
var json = require('./test.json');

utils.dump(json);
utils.dump(json.test); // hello
utils.dump(json["test"]); // hello

(i would add it as a comment but I'd need 50+ rep to do that) (我会将其添加为评论,但我需要50多名代表才能这样做)

Here is a complete sample 这是一个完整的样本

var casper = require('casper').create();

var json = require('test.json');
require('utils').dump(json);
casper.echo(json['test']);

casper.exit();

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM