Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

json.Unmarshal nested object into string or []byte

Tags:

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

like image 568
Ilia Choly Avatar asked Nov 20 '13 16:11

Ilia Choly


People also ask

How does JSON Unmarshal work?

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.

What does Unmarshal JSON mean?

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.

How do I read JSON data in Golang?

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.

How define JSON in Golang?

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.


1 Answers

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

like image 79
ANisus Avatar answered Sep 20 '22 14:09

ANisus