js写的代码生成脚本,json生成对应的go type对象
作json转换用
js脚本无甚何依赖,可以直接运行
执行前,按需更改文件
示例
var topname="Data"; var defaulttype="string"; var bson=true; //对应 mongodb var json=true; //http response var scheme=false; //http request->scheme var jdata={ "_id" : "564d5162e54b3106fb7badea", "macs" : [ "00-21-26-00-C8-B0" ], "time" : 1447907400, "timestr" : "2015-11-19 12:30", "shop":{ "name":"shop1" } }; String.prototype.firstToUpperCase=function(){ return this[0].toUpperCase()+this.substring(1); } var fun=(function(){ var otherobj=[]; var goobjstring=""; function getStruct(data,collectionname){ goobjstring+="type "+collectionname.firstToUpperCase()+" struct {\n"; var per="\t"; for(var key in data){ var newkey=key.firstToUpperCase(); goobjstring+=per +newkey+" "+getType(data[key],key); if (json||bson||scheme){ goobjstring+=‘ `‘; var temparr=[] if (json){ temparr.push(‘json:"‘+key+‘"‘); } if (bson){ temparr.push(‘bson:"‘+key+‘"‘); } if (scheme){ temparr.push(‘scheme:"‘+key+‘"‘); } goobjstring+=temparr.join(" "); goobjstring+=‘`‘; } goobjstring+="\n"; } goobjstring+="}\n"; while (otherobj.length>0){ var subobj=otherobj.pop(); getStruct(subobj.obj,subobj.key) } return goobjstring } function getType(obj,key){ var type=defaulttype; if(obj){ switch(obj.constructor) { case Array: type="[]"+getType(obj[0]||"",key.firstToUpperCase()) ; break; case Object: otherobj.push({key:key,obj:obj}); type=key.firstToUpperCase() break; case String: type="string" break; case Number: type="int" break; case Boolean: type="bool" break; default : } } return type; } return getStruct })() console.log(fun(jdata,topname))
结果
type Data struct { _id string `json:"_id" bson:"_id"` Macs []string `json:"macs" bson:"macs"` Time int `json:"time" bson:"time"` Timestr string `json:"timestr" bson:"timestr"` Shop Shop `json:"shop" bson:"shop"`}type Shop struct { Name string `json:"name" bson:"name"`}
代码是之前辅助go 开发写的
go的web框架
https://github.com/cclient/gowebframework
代码路径
https://github.com/cclient/gowebframework/blob/master/tool/code.js
时间: 2024-10-01 13:30:42