JSON factoury生成器

作者: MakingChoice | 来源:发表于2016-06-10 23:02 被阅读69次

    下面分享一个JSON生成器,主要可以生成如下所示的json结构:

    {
        type:"message_1",
        text1:"one two three",
        text2:"one two three",
        .....
    }
    

    其中type是指的是JSON的名字。

    下面是生成器代码:

    var sentinel=function(type,value,props){
        var copy=Object.create(null);//生成一个原型为null的对象
        if(props!=null){
            for(var prop in props){
                copy[prop]=props[prop]
            }
            copy["$type"]=type;
            copy.value=value;
            return copy;
        }
        else{
            return {$type:type,value:value}
        }    
    }
    module.exports={
        ref:function ref(path,props){
            return sentinel("ref", path, props);
        },
        atom:function atom(){
            return sentinel("atom",path,props)
        },
        undefined:function(){
            return sentinel("atom")
        },
        error:function(errorValue,props){
            return sentinel("error",errorValue,props)
        },
        .....//剩下可以自己填充了
    }
    

    这个方法支持AMD,可以通过require来获取。

    var jsonFactory=require(....);
    var atom = jsonFactory.atom("a string wrapped in an atom"); 
    // creates { $type: "atom", value: "a string wrapped in an atom" }
    var ref = jsonFactory.ref("todos[0].name"); 
    // creates { $type: "ref", value: ["todos", 0, "name"] }
    var error = jsonFactory.error("something bad happened."); 
    // creates { $type: "error", value: "something bad happened." }
    

    相关文章

      网友评论

        本文标题:JSON factoury生成器

        本文链接:https://www.haomeiwen.com/subject/ihvkdttx.html