Home >Backend Development >Golang >How can I pass the entire json string to a field of a nested structure when unmarshalling?
In PHP, when we need to pass the entire JSON string to a field of a nested structure, there is an easy way to do it. First, we need to make sure we have decoded the JSON string into a PHP array or object. We can then use the json_encode() function to encode the decoded array or object into a JSON string again. Next, we can assign the encoded JSON string to the target field. In this way, we have successfully passed the entire JSON string to the fields of the nested structure. This is a simple yet effective method that allows us to easily process JSON data in PHP.
I need to unmarshal a flat json string
data := `{"login":"Nickname","password":"some_pass","newPassword":"new_pass"}`
EnterUpdatePasswordRequest
Nested structure:
type SignInRequest struct { Login string `json:"login"` Password string `json:"password"` } type UpdatePasswordRequest struct { NewPassword string `json:"newPassword"` SignInData SignInRequest `<tag>` }
Unmarshal data
using all possible 8bf259f5a6144433b921fb8b7de94970
values into result
var result UpdatePasswordRequest json.Unmarshal([]byte(data), &result)
Give empty Login
and Password
:
result.SignInData.Login = "" result.SignInData.Password = ""
How should I define 8bf259f5a6144433b921fb8b7de94970
to get the correct values for the Login
and Password
fields?
If you want to use the name of 8bf259f5a6144433b921fb8b7de94970
, your json should be nested, not flat, like this:
data := `{"newPassword":"new_pass", "myTag":{"password":"some_pass", "login":"Nickname"}}`
If you can't change your json, the structure (aka .struct embedding) should be composed like this:
type SignInRequest struct { Login string `json:"login"` Password string `json:"password"` } type UpdatePasswordRequest struct { NewPassword string `json:"newPassword"` SignInRequest }
The above is the detailed content of How can I pass the entire json string to a field of a nested structure when unmarshalling?. For more information, please follow other related articles on the PHP Chinese website!