智能合约从入门到精通:Lib工具库(二)

简介:上一节,我们介绍智能合约开发中常用的Lib工具库的第一部分。由于内容较长,工具库我们将分两部分介绍,本文将介绍Lib工具库的第二部分:LibJson 、LibStack和LibLog。

LibJson

LibJson主要封装了对JSON格式的字符串一些操作;

支持直接调用、using for *;调用

注意:正如在Lib工具库说明中提到的,LibJson 库的使用稍微有点特殊:

不管是直接调用,还是using for *;方式调用,在合约方法中,如果要使用一次、或者多次LibJson库中的方法,则在第一次使用LibJsos库方法前,需要对被操作的json字符串进行如下操作:

//字符串入栈

LibJson.push(_json);

在最后一个LibJsos库方法之后,要进行如下操作

//出栈

LibJson.pop();

示例:

pragma solidity ^0.4.2;

 

import "./utillib/LibJson.sol";

 

contract TestManager {

 

    using LibJson for *;

 

    string[] public _arr;

 

    function test() constant returns(bool _ret) {

        string memory _json = "{\"errno\":27,\"hash\":\"0xf16a2a734ccf0456807e166ad310ec7767f71e8d4003154b73596741683c6433\",\"nodeId\":\"JZNCGP\",\"type\":1}";

       // step01: 字符串入栈

       LibJson.push(_json);

       // step02: 操作字符串,判断自否为一个合法的json格式

       bool isJson = _json.isJson();   

       //或者直接调用

       //bool isJson = LibJson.isJson(_json);

 

       _json.jsonRead("nodeId");     // "JZNCGP"

       // step03: 出栈

       LibJson.pop();

    }

}

  • LibJson.push()  LibJson.pop() 一定是成对出现的;
  • 当对字符串的操作结束后务必调用pop将栈中的元素移除掉;

JSON格式判断

描述:判断指定串是否为标准的JSON格式

结构定义

function isJson(string _json) internal constant returns(bool _ret);

示例

string memory _json = "{\"errno\":27,\"hash\":\"0xf16a2a734ccf0456807e166ad310ec7767f71e8d4003154b73596741683c6433\",\"nodeId\":\"JZNCGP\",\"type\":1}";

bool _ret= _json.isJson();        //  _ret = true

读取JSON中key的值

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值