Home > Article > Backend Development > Unmarshal partial data bytes into a custom structure
I have data in the form of map[string][]byte
, where key is the json field tag of the structure, value is a slice of bytes.
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 to unmarshal the corresponding field data into a Tweet structure, which can contain any type of field, i.e. slice/map/custom type/pointer type? Do I have to map each field's data individually one by one or is there any general way?
I tried marshalling the entire data and unmarshalling it back into a struct type, but it seems like it internally modifies the actual data and doesn't work.
bytes, err := json.Marshal(data) var t Tweet err = json.Unmarshal(bytes,&t)
I don't think you mentioned your error, but the following worked for me. You can try 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) }
The above is the detailed content of Unmarshal partial data bytes into a custom structure. For more information, please follow other related articles on the PHP Chinese website!