duanmorong9597 2018-08-03 08:28 采纳率: 100%
浏览 115
已采纳

如何在golang中轻松编辑JSON类型(例如Node.js)

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?

  • 写回答

2条回答 默认 最新

  • donglian6625 2018-08-03 09:09
    关注

    You usually have to choose between performance and simplicity.

    If you need performance, then model your JSON input with structs, and then you can easily get/set different parts using selectors on your structs, and you also get Go's type safety for free. Note: there are libs and online services which automatically generate Go structs from input JSON text, such as https://mholt.github.io/json-to-go/.

    If you choose simplicity, you may use 3rd party libs that allow easy manipulation of "dynamic" objects (e.g. maps and slices which are the result of unmarshaling such JSON input text).

    For one, there's github.com/icza/dyno (disclosure: I'm the author).

    Using dyno, the simplicity of the solution is close to that of JavaScript's. Since dyno operates on maps and slices, it may be slower for certain tasks, but for such simple one that is in your question, it may be even faster because it does not use reflection (only type assertion and type switches).

    Let's say the identifier src holds your input JSON text (may be a constant or a variable), then the Go code equivalent to yours is:

    var cowInfo interface{}
    if err := json.Unmarshal([]byte(src), &cowInfo); err != nil {
        panic(err)
    }
    
    eartag := map[string]string{
        "docType":      "reattachEartag",
        "flatEartagNo": "eartag206015",
        "rfidNo":       "rfid234234",
    }
    
    if breed, err := dyno.Get(cowInfo, "result", "breed"); err == nil {
        dyno.Set(breed, eartag, "earTag")
    } else {
        dyno.Set(cowInfo, map[string]interface{}{"earTag": eartag}, "result", "breed")
    }
    
    enc := json.NewEncoder(os.Stdout)
    enc.SetIndent("", "  ")
    if err := enc.Encode(cowInfo); err != nil {
        panic(err)
    }
    

    The above code unmarshals the input JSON, performs the processing / modification, and finally it marshals the result onto your console.

    Here's the complete app: Go Playground. Note: you can't run it on the Go Playground because it imports github.com/icza/dyno (and importing 3rd party libs is not allowed there), you have to run it locally (after go getting dyno).

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥20 wireshark抓不到vlan
  • ¥20 关于#stm32#的问题:需要指导自动酸碱滴定仪的原理图程序代码及仿真
  • ¥20 设计一款异域新娘的视频相亲软件需要哪些技术支持
  • ¥15 stata安慰剂检验作图但是真实值不出现在图上
  • ¥15 c程序不知道为什么得不到结果
  • ¥40 复杂的限制性的商函数处理
  • ¥15 程序不包含适用于入口点的静态Main方法
  • ¥15 素材场景中光线烘焙后灯光失效
  • ¥15 请教一下各位,为什么我这个没有实现模拟点击
  • ¥15 执行 virtuoso 命令后,界面没有,cadence 启动不起来