我正在使用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