我用过:
https://mholt.github.io/json-to-go/
进行转换
{
"id": 5533,
"action": "/api/v1/private/subscribe",
"arguments": {
"instrument": ["BTC-19DEC14"],
"event": ["order_book", "trade", "user_order"]
}
}
进入
type AutoGenerated struct {
ID int `json:"id"`
Action string `json:"action"`
Arguments struct {
Instrument []string `json:"instrument"`
Event []string `json:"event"`
} `json:"arguments"`
}
然后我尝试如下在Go代码中使用此代码:
package main
import (
"flag"
"os"
)
var addr = flag.String("addr", "www.deribit.com", "http service address")
func main() {
type AutoGenerated struct {
ID int `json:"id"`
Action string `json:"action"`
Arguments struct {
Instrument []string `json:"instrument"`
Event []string `json:"event"`
} `json:"arguments"`
}
json := &AutoGenerated{
ID: 42,
Action: "/api/v1/public/getorderbook",
Arguments: struct {
Instrument: ["BTC-19DEC14"],
Event: ["order_book", "trade", "user_order"],
},
}
}
我在Arguments
中遇到错误,即我的结构在结构中。
如何将JSON转换为可以在go中使用的变量?
答案 0 :(得分:1)
示例是..
package main
import (
"flag"
"fmt"
)
var addr = flag.String("addr", "www.deribit.com", "http service address")
type Arguments struct {
Instrument []string `json:"instrument"`
Event []string `json:"event"`
}
type AutoGenerated struct {
ID int `json:"id"`
Action string `json:"action"`
Argument Arguments `json:"arguments"`
}
func main() {
json := &AutoGenerated{
ID: 42,
Action: "/api/v1/public/getorderbook",
Argument: Arguments{
Instrument: []string{"BTC-19DEC14"},
Event: []string{"order_book", "trade", "user_order"},
},
}
fmt.Println(json)
}