The below is my sample code in Go. I want to parse the value of B and check value of key 'status'
package main
import (
"encoding/json"
"fmt"
)
type ValidateUser struct {
UserName, status, sessionID, timestamp string
}
func main() {
// This JSON contains an int array.
B := "{\"UserName\": \"Moulali\",\"status\": \"valid_user\"}"
fmt.Println("outside if")
fmt.Println("ValueOfB = %v", B)
bytes := []byte(B)
var validateUser ValidateUser
json.Unmarshal(bytes, &validateUser)
if validateUser.status == "valid_user" {
fmt.Printf("Valid User")
}
}
status
should be exported (ValidateUser.Status
). Just one slight modification to your code:
package main
import (
"encoding/json"
"fmt"
)
type ValidateUser struct {
UserName string
// export Status, and map to json field `status`
Status string `json: "status"`
sessionID string
timestamp string
}
func main() {
// This JSON contains an int array.
B := "{\"UserName\": \"Moulali\",\"status\": \"valid_user\"}"
fmt.Println("outside if")
fmt.Println("ValueOfB = %v", B)
bytes := []byte(B)
var validateUser ValidateUser
json.Unmarshal(bytes, &validateUser)
// reference ValidateUser.Status (capital s)
if validateUser.Status == "valid_user" {
fmt.Printf("Valid User")
}
}
Link to code: https://play.golang.org/p/WN4cOz_YBLF
json
package methods can only deal with public fields. Here, status
is a private field and it is not accessible form json.Marshal
or json.Unmarshal
.
If you want to have the field name as status
, you can specify that in json tag
.
See the example:
package main
import (
"encoding/json"
"fmt"
)
type ValidateUser struct {
UserName string `json:"UserName"`
Status string `json:"Status"`
sessionID, timestamp string
}
func main() {
// This JSON contains an int array.
B := "{\"UserName\": \"Moulali\",\"status\": \"valid_user\"}"
fmt.Println("outside if")
fmt.Println("ValueOfB = %v", B)
bytes := []byte(B)
var validateUser ValidateUser
json.Unmarshal(bytes, &validateUser)
if validateUser.Status == "valid_user" {
fmt.Printf("Valid User: %v
", validateUser)
jsonMarshalled, _ := json.Marshal(validateUser) //checking marshal
fmt.Println(string(jsonMarshalled))
}
}
Output:
outside if
ValueOfB = %v {"UserName": "Moulali","status": "valid_user"}
Valid User: {Moulali valid_user }
{"UserName":"Moulali","Status":"valid_user"}