如何从geth加载json文件

问题描述

也许是因为我不方便使用js,但是如何从geth控制台加载.json文件?我希望这样做是为了避免笨拙地为每个合同os.Stdin复制粘贴每个原始abi内容。我知道控制台是javascript,因此我尝试使用Write()(使用nodejs很容易),但是它不起作用。在geth(js控制台)中无法像我在python中轻松腌制文件一样,加载var abi_1 = [...]; var abi_2 = [...]; ...并将其存储在变量abi_1中吗?谢谢,希望这个问题对社区有意义。

解决方法

如文档[1]中所指定,geth控制台在go中使用称为goja [2]的ECMAScript实现。据我了解,经典JS(因此没有nodejs)没有任何IO功能。

但是,也许您可​​以使用控制台中提供的“ loadScript”功能+一些bash。

例如,假设您的JSON文件位于/tmp/abi.json中。您所有的JS操作都可以存储在另一个文件中(例如/tmp/operations.js)。

您可以使用geth attach http://localhost:8545 --exec "var abi = $(cat /tmp/abi.json); loadScript('/tmp/operations.js')"

例如: /tmp/file.json包含{ 'test': 'Hello,world'}

geth attach http://localhost:8545 --exec "var a = $(cat /tmp/file.json); console.log(a.test)"

将打印Hello,world!

这不是一个完美的解决方案,但它可能对您方便。

[1] https://geth.ethereum.org/docs/interface/javascript-console

[2] https://github.com/dop251/goja