我正在使用the PhantomJS gem从Ruby调用PhantomJS脚本。为什么我无法将JSON从Ruby发送到Phantomjs
当我需要将HTML发送到我打电话给的PhantomJS脚本时,我已经在我的应用程序中成功使用了该gem。
但是,当我尝试将JSON发送到我打电话给的PhantomJS脚本时,它失败了。
我打来的PhantomJS脚本是PhantomJS-Google-Charts。
我修改剧本的前几行改为:
var system = require('system');
var fs = require('fs');
var jsonData = fs.open(system.args[1], 'r'); // also tried 'rb'
// exports.generateChart = function(jsonData, callback){
var page = require('webpage').create();
page.viewportSize = {width: jsonData.options.width, height: jsonData.options.height};
我做了这几个变化,因为(a)尝试和失败的JSON直接发送到脚本作为参数我看了之后in situations like my own the only way to send JSON to PhantomJS is to save it to a file and then read it和(b)我没有将这个脚本作为另一个JavaScript脚本的模块调用 - 我直接从Ruby调用它 - 这意味着export
不适用于我。
在Ruby中,我这样做:
data = {"type" => "PieChart", "options" => {"title" => "Type of Fruit Eaten", "width" => "400", "height" => "300", "is3D" => true, "pieSliceText" => "value"},"columns" => {"Type" => "string", "Eaten" => "number"}, "rows" => {"Bananas" => 4, "Apples" => 2, "Oranges" => 6, "Mangoes" => 3}}.to_json
require 'tempfile'
file = Tempfile.new("foo")
file.write(data)
file.rewind
Phantomjs.run("./app/assets/javascripts/googleCharts.js", file.path)
那么,为什么我收到此错误:
"TypeError: 'undefined' is not an object (evaluating 'jsonData.options.width')\n\n ./app/assets/javascripts/googleCharts.js:43\n"
BTW,43行(在错误的统称)是:
page.viewportSize = {width: jsonData.options.width, height: jsonData.options.height};
当我在TextMate中打开临时文件,它看起来像这样:
{"type":"PieChart","options":{"title":"Type of Fruit Eaten","width":"400","height":"300","is3D":true,"pieSliceText":"value"},"columns":{"Type":"string","Eaten":"number"},"rows":{"Bananas":4,"Apples":2,"Oranges":6,"Mangoes":3}}
当我把它粘贴到JSONLint,它验证。
为什么我跑在PhantomJS命令行脚本(在该文件的路径粘贴而不是从system.args
调用它),我得到这个错误:
'page.viewportSize = {width: jsonData.options.width, height: jsonData.options.height};' is a cyclic structure
在这一点上,如果我只需键入jsonData.options.width
,我得到:
'jsonData.options.width' is a cyclic structure
如果我只需要输入jsonData,我得到:
undefined
当提供的数据,给我们最起码的必要证明的问题。更多的东西会浪费空间,并且使其更难处理。 – 2014-11-07 00:16:14
如果使用'file.puts data'而不是'file.write(data)',会发生什么? – 2014-11-07 00:21:32
与'file.write(data)'相同的结果 – 2014-11-07 05:14:28