JSON RawMessage 修改

huangapple go评论74阅读模式
英文:

JSON RawMessage Modification

问题

假设我有以下的 JSON 原始消息,我将其解析为组件结构,取出 JSON 值 v.id 和 v.name。然后将它们传递给一些 dfs 函数,并返回一些好的东西。然后我将它们重新赋值给 id 和 name。

我意识到在 for 循环内部,它已经更新为好的东西,但是当我退出 for 循环时,它并没有更新原始的 JSON 原始消息。有没有办法更新原始的 JSON 消息,而不仅仅在循环内部更新?

if err := json.Unmarshal(inputs.Components, &component); err != nil {
    panic(err)
}

for _, v := range component {
    if _, ok := map[v.id+"-"+v.Name]; ok {
        var c string
        var m string
        raw_info1, raw_info2 := dfs(v.id, v.Name, map, &c, &m)
        v.id = raw_info1
        v.name = raw_info2
    }
}
英文:

Let's say I have below json raw message, I unmarshal as component struct, taking json value out,v.id and v.name. Passed to some dfs function and return me with good things. I then assign them back to id and name.

I realize that within the for loop, it has been updated to good things, however, when I exit for loop, it doesn't update the original JSON raw message. Is there any way to update original JSON message instead of just within the loop?

if err := json.Unmarshal(inputs.Components, &component); err != nil {
			panic(err)
		}	

for _, v := range component {
		if _, ok := map[v.id+"-"+v.Name]; ok {
			var c string
			var m string
			raw_info1, raw_info2 := dfs(v.id, v.Name, map, &c, &m)
			v.id = raw_info1
			v.name = raw_info2
		}
	}

答案1

得分: 0

我假设在这种情况下,component是一个映射而不是结构体,否则你不能像那样进行迭代。
当你遍历components时,你通过值获取键和值。因此,你修改的不是components的元素,而是它们的副本。
要修改components,你应该重写你的逻辑,像这样:

component[key] = v
英文:

I assume component in this case is a map and not a struct, else you cannot iterate like that.
When you range over components, you get the key and value "by value". As such, what you modify is not an element of components, but their copy.
To modify the components you should rewrite you logic like:

component[key] = v

答案2

得分: 0

我实际上是将其还原,以便修改 unmarshall 原始 JSON 对象内的值。

英文:

I actually marshall back so that it will modify the value inside unmarshall raw json object

huangapple
  • 本文由 发表于 2021年2月26日 05:08:58
  • 转载请务必保留本文链接:https://go.coder-hub.com/66376457.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定