I have data in the form of map[string][]byte
, where key is the json field tag of that struct and the value is the byte slice.
Consider this example:
type Tweet struct {
UserId int `json:"user_id"`
Message string `json:"message"`
}
data = {
"user_id":<some bytes>,
"message":<some bytes>
}
var t Tweet
How can i unmarshal the corresponding field data into the Tweet struct which can contain any type of field i.e. slice/map/Custom type/pointer type? Do i have to individually map the data of every field one by one or is there any generic way also?
I tried Marshalling the whole data and the unmarshalling back to the struct type but it seems it modifies the actual data internally and it doesn't work.
bytes, err := json.Marshal(data)
var t Tweet
err = json.Unmarshal(bytes,&t)
I think you didn't mentioned about your error, but below is worked for me. You can try like this.
package main
import (
"encoding/json"
"fmt"
)
type Tweet struct {
UserId int `json:"user_id"`
Message string `json:"message"`
}
func main() {
// Example data: map of field tags to JSON-encoded byte slices
data := map[string]json.RawMessage{
"user_id": []byte(`123`), // Encoded as a JSON number
"message": []byte(`"Hello, world!"`), // Encoded as a JSON string
}
// Convert map to JSON
jsonData, err := json.Marshal(data)
if err != nil {
fmt.Println("Error marshalling map to JSON:", err)
return
}
// Unmarshal JSON into Tweet struct
var t Tweet
if err := json.Unmarshal(jsonData, &t); err != nil {
fmt.Println("Error unmarshalling JSON:", err)
return
}
// Output the result
fmt.Printf("Unmarshalled: %+v\n", t)
// Marshal the Tweet struct back into JSON
marshalledData, err := json.Marshal(t)
if err != nil {
fmt.Println("Error marshalling Tweet struct to JSON:", err)
return
}
// Output the marshalled JSON
fmt.Printf("Marshalled: %s\n", marshalledData)
}