javascript json转为 go struct 小工具代码

/**
 * Created by cdpmac on 15/10/20.
 */
var topname="Ap";
var jdata={
    "item": {
        "id": "55b71c374d65c9b50212d4ba",
        "contactName": "",
        "industries": [
            "生活服务",
            "小区"
        ],
        "hello":[
            {word:1},
            {word:2},
            {word:3}
        ],
        "coordinates": {
            "lat": 39.7229,
            "lng": 116.342
        }
    }
};
var defaulttype="string";



var otherobj=[];

String.prototype.firstToUpperCase=function(){
    return this[0].toUpperCase()+this.substring(1);
}
var goobjstring="";
function getStruct(data,collectionname){
    goobjstring+="type "+collectionname.firstToUpperCase()+" struct {
";
    var per="	";
    for(var key in data){
        var newkey=key.firstToUpperCase();
        goobjstring+=per +newkey+" "+getType(data[key],key)+' `json:"'+key+'" bson:"'+key+'"`'+"
"
    }
    goobjstring+="}
";
    while (otherobj.length>0){
        var subobj=otherobj.pop();
        getStruct(subobj.obj,subobj.key)
    }
}


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;
}

getStruct(jdata
    ,topname)
console.log(goobjstring);

执行结果

type Ap struct {
    Item Item `json:"item" bson:"item"`
}
type Item struct {
    Id string `json:"id" bson:"id"`
    ContactName string `json:"contactName" bson:"contactName"`
    Industries []string `json:"industries" bson:"industries"`
    Hello []Hello `json:"hello" bson:"hello"`
    Coordinates Coordinates `json:"coordinates" bson:"coordinates"`
}
type Coordinates struct {
    Lat int `json:"lat" bson:"lat"`
    Lng int `json:"lng" bson:"lng"`
}
type Hello struct {
    Word int `json:"word" bson:"word"`
}
原文地址:https://www.cnblogs.com/zihunqingxin/p/4939441.html