AE 面板:将对象从 JS 发送到 JSX

AE Panel: Send obj from JS to JSX

我正在为 After Effects 编写一个面板,并试图将一个对象从我的 main.js 发送到我的 jsx 文件。从我可以找到的样本中,他们说我不能发送对象,但必须对 obj 进行 stringify() 并传递它。

我试过发送对象和字符串化对象的字符串 - 两者都不适合我。

main.js

var profileUI = {
     script: '',
     data: {
          csv:    $('#csv')[0].checked,
          feed:   $('#json')[0].checked,
          gs:     $('#googleSheets')[0].checked
     },
}
var csInterface = new CSInterface();
csInterface.evalScript('$._ext_SB.batch("' + JSON.stringify(profileUI) + '"")' );

myFunctions.jsx

$._ext_SB={
    batch : function(profileUI) {

        var str = "";
        for (prop in profileUI) {
          str += prop + " [" + typeof profileUI[prop] + "]: " + profileUI[prop] + ".\n";
        }
        alert(str);
    },
};

我收到一个错误:无法在第 1 行 运行 编写脚本。预期:)

它似乎没有得到一个实际的字符串,就像我上面提到的,试图传递一个对象也不起作用(那会更好)。

这里有三个问题。参见:

JavaScript

中的语法错误

您在对 evalScript 的调用中有一个额外的双引号 (") 字符。这个:

csInterface.evalScript('$._ext_SB.batch("' + JSON.stringify(profileUI) + '"")' );

应该是这样的(注意删除最后两个 " 字符之一):

csInterface.evalScript('$._ext_SB.batch("' + JSON.stringify(profileUI) + '")' );

JSON需要转义

正如您所指出的 ,您需要对 JSON 字符串中的 " 字符进行转义,以便在 evalScript() 处理时正确地取消转义.这导致:

csInterface.evalScript('$._ext_SB.batch("' + JSON.stringify(profileUI).replace(/"/g,'\"') + '")' );

为清楚起见,使用 .replace(/"/g,'\"').

完成转义

evalScript 不自动解析 JSON

您需要在 profileUI 参数上调用 JSON.parse() 以取回对象版本。参见:

$._ext_SB={
    batch : function(_profileUI) {
        // Convert the input string back into an object.
        var profileUI = JSON.parse(_profileUI);

        // Everything else should work okay...
        var str = "";
        // ...
    }
}

一些注意事项:

  1. 您从 JSON.parse() 返回的对象将是一个简单的对象 - 它将包含与您调用 JSON.stringify() 的对象相同的属性,但它没有任何关联的函数。
  2. ExtendScript 不会自动提供 JSON 支持。如果启动面板时它存在于应用程序中,那是因为所有面板(包括 Adob​​e 构建的面板)共享一个 ExtendScript 上下文。一些 Adob​​e 面板已经包含 JSON 库,您通常可以使用它。但是,如果您不能使用 JSON,您将需要自己包含一个兼容的 JSON 库。提到了一些 here.

这行代码...

csInterface.evalScript('$._ext_SB.batch("' + JSON.stringify(profileUI) + '")' );

需要更改为:

csInterface.evalScript('$._ext_SB.batch("' + JSON.stringify(profileUI).replace(/"/g,'\"') + '")' );

JSON.stringify 创建了一个有效的字符串,但是当我尝试通过 '"'+someString+'"' 创建字符串的源代码时,这仅在 someString 本身不包含任何引号的情况下才有效。 replace() 用 \" 替换所有引号,以便它可以作为有效字符串发送。

js端也可以使用模板字符串: https://developer.mozilla.org/de/docs/Web/JavaScript/Reference/template_strings

evalScript(`$._ext_SB.batch('${encodeURIComponent(JSON.stringify(profileUI))}')`);

单引号包含要将其作为字符串参数传递给 jsx 函数的字符串。

并且 encodeURIComponent 转义字符串可能包含的所有内容,在将其发送到 jsx 时可能会导致问题。

然后,在 jsx 中反转编码和字符串化:

var profileUI = JSON.parse(decodeURIComponent(_profileUI));

replace(/"/g,'\"') 仅替换由 JSON.parse.

生成的双引号

可能导致问题的字符串还可能包含双引号以外的其他特殊字符。