0

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

1 Answers1

1

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$ 
Crowman
  • 25,242
  • 5
  • 48
  • 56
  • Thanks, that worked. Where could I have learned that I would have needed to use the `bson` field tag? –  May 07 '19 at 15:50
  • 1
    @Houseman: Good question. The docs don't seem to go out of their way to tell you about it, but there's some info [here](https://godoc.org/go.mongodb.org/mongo-driver/bson/bsoncodec#StructTagParserFunc) for example. But in general if you're having such issues and the labels in your file don't exactly match the names of your struct fields, then some problem with the field tags is a possibility which immediately springs to mind. – Crowman May 07 '19 at 16:30