I try to convert to node.js code into golang code.
This is my sample JSON.
{
"result": {
"birthInfo": {
"birthYmd": "2018-07-25",
"cattleNo": "cow001",
"docType": "registerBirth",
"lsTypeNm": "redbull",
"monthDiff": "2018-07",
"nationNm": "japan",
"regType": "directly",
"regYmd": "2018-07-25",
"sexNm": "farm001"
},
"breed": {
"dead": {
"deadCd": "deadcd20180725",
"deadYmd": "2018-07-25",
"docType": "reportDeCattle"
},
"earTag": {
"docType": "reattachEartag",
"flatEartagNo": "eartag206015",
"rfidNo": "rfid234234"
}
}
}
}
When using node.js, it is easy to get or access json data like this.
let cowbytes = await stub.getState("cow001");
var cowInfo = JSON.parse(cowbytes);
var eartag = {
docType: 'reattachEartag',
flatEartagNo: "eartag206015",
rfidNo: "rfid234234",
};
if (cowInfo.breed) {
cowInfo.breed['earTag'] = eartag;
} else {
cowInfo.breed = {
earTag: eartag
};
}
await stub.putState(args[0], Buffer.from(JSON.stringify(cowInfo)));
And this is my golang code which I benchmark node.js code.
cowbytes, _: = APIstub.GetState("cow001")
if cowbytes == nil {
return shim.Error("Incorrect value. No cattle Info..")
}
var cowInfo map[string] interface {}
json.Unmarshal(cowbytes, & cowInfo)
eartag: = make(map[string] interface {})
eartag["docType"] = "reattachEartag"
eartag["flatEartagNo"] = string("eartag206015")
eartag["rfidNo"] = string("rfid234234")
_, exists: = cowInfo["breed"]
if exists {
inputJSON,
err: = json.Marshal(cowInfo["breed"])
fmt.Println(err)
out: = map[string] interface {} {}
json.Unmarshal([] byte(inputJSON), & out)
out["earTag"] = struct {
EarTag map[string] interface {}
`json:"earTag"`
} {
eartag,
}
cowInfo["breed"] = out
}
else {
cowInfo["breed"] = struct {
EarTag map[string] interface {}
`json:"earTag"`
} {
eartag,
}
}
cattleAsBytes, _: = json.Marshal(cowInfo)
APIstub.PutState(string("cow001"), cattleAsBytes)
Although my golang file works fine, I think it is not only hard to write code but also performane is bad(duplicate marshal & unmarshal).
how can I easily control JSON type in Golang.
Does anyone have an idea?