[英]How do I preserve line breaks from Etherscan API using R and JSON?
我正在使用Etherscan API下載某些已驗證合同的Solidity代碼。 盡管這樣做確實有效,但我丟失了需要保留的換行符。
例如,考慮https://etherscan.io/address/0xb494e1195e0c6bad435be4c9fa0b36ce94bfd7d1#code上已驗證合同的代碼
該合同的Solidity代碼片段為:
pragma solidity ^0.4.18;
/**
* @title SafeMath
* @dev Math operations with safety checks that throw on error
*/
library SafeMath {
function mul(uint256 a, uint256 b) internal pure returns (uint256) {
uint256 c = a * b;
assert(a == 0 || c / a == b);
return c;
}
function div(uint256 a, uint256 b) internal pure returns (uint256) {
// assert(b > 0); // Solidity automatically throws when dividing by 0
uint256 c = a / b;
// assert(a == b * c + a % b); // There is no case in which this doesn't hold
return c;
}
more code....
最終,我希望將Solidity代碼存儲為包含換行符的字符串,即我想要
str_a <- "pragma solidity ^0.4.18;\\n\\n/**\\n* @title SafeMath\\n* @dev Math operations with safety checks that throw on error\\n*/\\nlibrary SafeMath {\\nfunction mul(uint256 a, uint256 b) internal pure returns (uint256) {\\nuint256 c = a * b;\\nassert(a == 0 || c / a == b);\\nreturn c;\\n}\\nfunction div(uint256 a, uint256 b) internal pure returns (uint256) {\\n// assert(b > 0); // Solidity automatically throws when dividing by 0\\nuint256 c = a / b;\\n// assert(a == b * c + a % b); // There is no case in which this doesn't hold\\nreturn c;\\n}"
但是,我編寫的代碼會產生
pragma solidity ^0.4.18;/** * @title SafeMath * @dev Math operations with safety checks that throw on error */library SafeMath { function mul(uint256 a, uint256 b) internal pure returns (uint256) { uint256 c = a * b; assert(a == 0 || c / a == b); return c; } function div(uint256 a, uint256 b) internal pure returns (uint256) { // assert(b > 0); // Solidity automatically throws when dividing by 0 uint256 c = a / b; // assert(a == b * c + a % b); // There is no case in which this doesn't hold return c; }
我的產生輸出的代碼如下,其中gstr_api_key是在代碼前面定義的表示API密鑰的全局字符串:
str_address <- "0xb494e1195e0c6bad435be4c9fa0b36ce94bfd7d1"
# Build string needed for URL
str_APIAction <- "/api?module=contract&action=getsourcecode&address="
str_APIKey <- paste("&apikey=", gstr_api_key, sep="")
str_path <- paste(str_APIAction, str_address, str_APIKey, sep="")
# Send request to API
raw_result <- httr::GET(url = gstr_eth_url, path = str_path)
# Convert response in to useful
raw_char <- rawToChar(raw_result$content)
raw_list <- jsonlite::fromJSON(raw_char)
str_a <- raw_list$result[1]
我對JSON格式的了解有限,但我知道JSON中不允許換行符。 那是對的嗎?
如何修改代碼,以便獲得所需的輸出?
我已經解決了問題-無法使用API完成。 而是使用httr和XML庫抓取頁面。 最后很容易
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.