【问题标题】:Can't use JSON string from PHP in casperjs无法在 casperjs 中使用来自 PHP 的 JSON 字符串
【发布时间】:2014-06-16 14:10:49
【问题描述】:

我无法在 args 中设置 json 以在 casperjs 脚本中使用它。

我正在启动第一个 casperjs 脚本,它在 php 文件中返回对象,然后我需要在另一个文件中使用它。 我试图让它像这样:

$command = "$casperjs $script $arg0";
$result = shell_exec($command);
$json_data = json_decode($result, true);
//here im getting some data from json but dont change it
$arg1 = json_encode($json_data); // i ried take $result but have the same result
$command = "$casperjs $script2 $arg1";
$json_data = shell_exec($command);

这里我有错误:

SyntaxError: Unable to parse JSON string 

$结果

{ "url": "bilko.com", "webPages": [ { "url": "bilko.com", "links": [ "/site-map", "/en/", "/biography", "/gallery", "/services", "/contacts", "/gallery/corporative", "/gallery/wedding", "/gallery/birthday", "/gallery/teambuilding" ], "content": "\n\t\n\t\t\n\t\n\t \n \n \n \n \n \n" } ], "menus": { "identifier": ".menu", "items": [ [ { "text": "Биография", "url": "/biography" }, { "text": "Галерея", "url": "/gallery" }, { "text": "Услуги", "url": "/services" }, { "text": "Контакты", "url": "/contacts" } ] ] }, "top": { "content": "/images/topLogo.png", "identifier": "header" }, "footer": { "content": "Профессиональный ведущий\nНиколай Билько\n+7 925 025 33 27\n", "identifier": "footer" }, "socBtns": [ [ "https://vk.com/id23333446", "/images/socBtns/vk.png" ] ], "sitemap": [ "/biography", "/contacts", "/en/", "/gallery", "/gallery/birthday", "/gallery/corporative", "/gallery/teambuilding", "/gallery/wedding", "/services", "/site-map", null ] }

在 script2 中我正在尝试制作

site = JSON.parse(system.args[4]);

【问题讨论】:

  • 那么,$result 包含什么?
  • 将对象添加到您的问题中,而不是作为评论。

标签: javascript php json casperjs


【解决方案1】:

如果您想将数据传递给 casperjs,则将其写入文件并将路径传递给 casperjs 脚本。然后你可以read文件的内容:

var fs = require("fs");
var site = JSON.parse(fs.read(system.args[4]));

您可以将 JSON 字符串写入 php 脚本中的临时文件:

$tmp = tempnam(dirname(__FILE__), "tmp");
file_put_contents($tmp, json_encode($json_data));
$json_data = shell_exec("$casperjs $script2 $tmp");
unlink($tmp);

可能的故障可能是:

  • 参数长度限制(大约 120 个字符)
  • $arg1 中不能有空格
  • 您的 shell 可能会尝试解释 JSON 字符串中的 "",因此请将整个字符串包含在 '' 中:"$casperjs $script2 '$arg1'"
  • 那里还有非 ansi 字符,可能会根据 shell 中断调用

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2014-05-30
    • 2021-12-17
    • 1970-01-01
    • 1970-01-01
    • 2019-08-07
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多