golang json 'true' is not True?

WBOY
Release: 2024-02-10 12:00:11
forward
442 people have browsed it

golang json\'true\'不是True?

php editor Xigua today will answer a question about golang: "Isn't json 'true' in golang True?" In golang, the Unmarshal function in the json package When parsing JSON data into a Go language structure, 'true' is not equal to True for Boolean type values. This is because in JSON, Boolean type values ​​are represented by lowercase 'true' and 'false', while in Go language, Boolean type values ​​are represented by uppercase True and False. This subtle difference may cause some problems and confusion, so we need to pay attention to this difference when using golang to parse JSON data.

Question content

I just learned golang, convert json to struct, and get the boolean value is always false. If my json "remembers": true, the resulting boolean value is true, how to solve it? My code

package main

import (
    "encoding/json"
    "fmt"
)

type AdminInfoRequest struct {
    Id          uint   `json:"id"`
    UserName    string `json:"username"`
    Password    string `json:"password"`
    CaptchaId   string `json:"captcha_id"`
    Captcha     string `json:"captcha"`
    Remember    bool   `json:"remember"`
    Status      uint   `json:"status"`
    GroupId     uint   `json:"group_id"`
    OldPassword string `json:"old_password"`
    RePassword  string `json:"re_password"`
}

func main() {
    var s AdminInfoRequest
    j := `{"username":"admin","remember":"true"}`
    json.Unmarshal([]byte(j), &s)
    fmt.Println(s.UserName)
    fmt.Println(s.Remember)
}
Copy after login

Solution

In json, "true" is a string value. Try this:

j := `{"username":"admin","remember":true}`
Copy after login

The above is the detailed content of golang json 'true' is not True?. For more information, please follow other related articles on the PHP Chinese website!

Related labels:
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!