I'm trying to Unmarshal some json so that a nested object does not get parsed but just treated as a string
or []byte
.
So I want to get the following:
{ "id" : 15, "foo" : { "foo": 123, "bar": "baz" } }
Unmarshaled into:
type Bar struct { ID int64 `json:"id"` Foo []byte `json:"foo"` }
I get the following error:
json: cannot unmarshal object into Go value of type []uint8
playground demo
To unmarshal a JSON array into a slice, Unmarshal resets the slice length to zero and then appends each element to the slice. As a special case, to unmarshal an empty JSON array into a slice, Unmarshal replaces the slice with a new empty slice.
Go's terminology calls marshal the process of generating a JSON string from a data structure, and unmarshal the act of parsing JSON to a data structure.
json is read with the ioutil. ReadFile() function, which returns a byte slice that is decoded into the struct instance using the json. Unmarshal() function. At last, the struct instance member values are printed using for loop to demonstrate that the JSON file was decoded.
JSON is a widely used format for data interchange. Golang provides multiple encoding and decoding APIs to work with JSON including to and from built-in and custom data types using the encoding/json package. Data Types: The default Golang data types for decoding and encoding JSON are as follows: bool for JSON booleans.
I think what you are looking for is the RawMessage type in the encoding/json
package.
The documentation states:
type RawMessage []byte
RawMessage is a raw encoded JSON object. It implements Marshaler and Unmarshaler and can be used to delay JSON decoding or precompute a JSON encoding.
Here is a working example of using RawMessage:
package main import ( "encoding/json" "fmt" ) var jsonStr = []byte(`{ "id" : 15, "foo" : { "foo": 123, "bar": "baz" } }`) type Bar struct { Id int64 `json:"id"` Foo json.RawMessage `json:"foo"` } func main() { var bar Bar err := json.Unmarshal(jsonStr, &bar) if err != nil { panic(err) } fmt.Printf("%+v\n", bar) }
Output:
{Id:15 Foo:[123 32 34 102 111 111 34 58 32 49 50 51 44 32 34 98 97 114 34 58 32 34 98 97 122 34 32 125]}
Playground
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With