How can I pass the entire json string to a field of a nested structure when unmarshalling?

WBOY
Release: 2024-02-13 10:27:10
forward
983 people have browsed it

如何在解组时将整个 json 字符串传递到嵌套结构的字段?

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.

Question content

I need to unmarshal a flat json string

data := `{"login":"Nickname","password":"some_pass","newPassword":"new_pass"}`
Copy after login

EnterUpdatePasswordRequestNested structure:

type SignInRequest struct {
    Login    string `json:"login"`
    Password string `json:"password"`
}

type UpdatePasswordRequest struct {
    NewPassword string        `json:"newPassword"`
    SignInData  SignInRequest `<tag>`
}
Copy after login

Unmarshal data using all possible <tag> values ​​into result

var result UpdatePasswordRequest
json.Unmarshal([]byte(data), &result)
Copy after login

Give empty Login and Password:

result.SignInData.Login = ""
result.SignInData.Password = ""
Copy after login

How should I define <tag> to get the correct values ​​for the Login and Password fields?

Workaround

If you want to use the name of <tag>, your json should be nested, not flat, like this:

data := `{"newPassword":"new_pass", "myTag":{"password":"some_pass", "login":"Nickname"}}`
Copy after login

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
}
Copy after login

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!

source:stackoverflow.com
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!