英文:
Golang changing value in json.RawMessage
问题
我有一个json.RawMessage,为了获取它,我需要向API发送一个请求。我的问题是,我需要对这个消息进行更改,只需要更改一个字段,所以我的问题是最有效的方法是什么?
json.RawMessage
{
"make": "VW",
"model": "ARTEON",
"version": "2.0 TDI",
"year_min": 2017,
"power_ps": 200,
"fuel": "diesel",
"body_type": "sedan",
"currency": "EUR",
"co2_emission": 130
}
例如,我想将燃料类型从柴油更改为汽油。
期望的输出
{
"make": "VW",
"model": "ARTEON",
"version": "2.0 TDI",
"year_min": 2017,
"power_ps": 200,
"fuel": "gasoline",
"body_type": "sedan",
"currency": "EUR",
"co2_emission": 130
}
英文:
I have json.RawMessage and for getting I need to send a request to API. My problem is that I need to make a change in that message I just need to change one field, so my question is what is the most effective way to do it
json.RawMessage
{
"make": "VW",
"model": "ARTEON",
"version": "2.0 TDI",
"year_min": 2017,
"power_ps": 200,
"fuel": "diesel",
"body_type": "sedan",
"currency": "EUR",
"co2_emission": 130
}
so for example I want to change fuel type from diesel to gasoline
expected output
{
"make": "VW",
"model": "ARTEON",
"version": "2.0 TDI",
"year_min": 2017,
"power_ps": 200,
"fuel": "gasoline",
"body_type": "sedan",
"currency": "EUR",
"co2_emission": 130
}
答案1
得分: 0
除了@mkopriva的评论(我认为这是更可取的方式),你可以尝试使用map而不是struct(如果struct对你不适用)。
package main
import (
"encoding/json"
"fmt"
)
var rm = json.RawMessage(`{
"make": "VW",
"model": "ARTEON",
"version": "2.0 TDI",
"year_min": 2017,
"power_ps": 200,
"fuel": "diesel",
"body_type": "sedan",
"currency": "EUR",
"co2_emission": 130
}`)
func main() {
var objmap map[string]interface{}
err := json.Unmarshal(rm, &objmap)
if err != nil {
panic(err)
}
objmap["fuel"] = "gasoline"
result, err := json.Marshal(objmap)
if err != nil {
panic(err)
}
fmt.Println(string(result))
}
https://go.dev/play/p/nue-SA-LGVf
英文:
In addition to the comment from @mkopriva(That I think is the more preferable way), you can try using a map instead of a struct(If a struct is not applicable to you).
package main
import (
"encoding/json"
"fmt"
)
var rm = json.RawMessage(`{
"make": "VW",
"model": "ARTEON",
"version": "2.0 TDI",
"year_min": 2017,
"power_ps": 200,
"fuel": "diesel",
"body_type": "sedan",
"currency": "EUR",
"co2_emission": 130
}`)
func main() {
var objmap map[string]interface{}
err := json.Unmarshal(rm, &objmap)
if err != nil {
panic(err)
}
objmap["fuel"] = "gasoline"
result, err := json.Marshal(objmap)
if err != nil {
panic(err)
}
fmt.Println(string(result))
}
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论