Reputation:
I'm trying to unmarshal extended JSON into a struct using UnmarshalExtJSON
from go.mongodb.org/mongo-driver/bson
It's giving me an error: invalid request to read array
How can I unmarshal this data into my struct?
MVCE:
package main
import (
"fmt"
"go.mongodb.org/mongo-driver/bson"
)
func main() {
var json = "{\"data\":{\"streamInformation\":{\"codecs\":[\"avc1.640028\"]}}}"
var workflow Workflow
e := bson.UnmarshalExtJSON([]byte(json), false, &workflow)
if e != nil {
fmt.Println("err is ", e)
// should print "err is invalid request to read array"
return
}
fmt.Println(workflow)
}
type Workflow struct {
Data WorkflowData `json:"data,omitempty"`
}
type WorkflowData struct {
StreamInformation StreamInformation `json:"streamInformation,omitempty"`
}
type StreamInformation struct {
Codecs []string `json:"codecs,omitempty"`
}
I'm using go version 1.12.4 windows/amd64
Upvotes: 0
Views: 936
Reputation: 25908
You're unmarshalling using the bson
package, but you're using json
struct field tags. Change them to bson
struct field tags and it should work for you:
package main
import (
"fmt"
"go.mongodb.org/mongo-driver/bson"
)
func main() {
var json = "{\"data\":{\"streamInformation\":{\"codecs\":[\"avc1.640028\"]}}}"
var workflow Workflow
e := bson.UnmarshalExtJSON([]byte(json), false, &workflow)
if e != nil {
fmt.Println("err is ", e)
return
}
fmt.Println(workflow)
}
type Workflow struct {
Data WorkflowData `bson:"data,omitempty"`
}
type WorkflowData struct {
StreamInformation StreamInformation `bson:"streamInformation,omitempty"`
}
type StreamInformation struct {
Codecs []string `bson:"codecs,omitempty"`
}
with output:
paul@mac:bson$ ./bson
{{{[avc1.640028]}}}
paul@mac:bson$
Upvotes: 1