Home > Article > Backend Development > json.Unmarshal doesn't work even with exported fields
php editor Zimo reminds you that even when deserializing JSON, the json.Unmarshal function will not work properly if there are exported fields. This is because the JSON parser can only parse exported fields and cannot recognize non-exported fields. Therefore, when using the json.Unmarshal function for deserialization, you need to ensure that the required fields are exported fields, otherwise the JSON data will not be parsed correctly. This is an important issue to pay attention to when using JSON serialization and deserialization. I hope it will be helpful to you.
json file:
{ "student_class": [ { "student_id": 1, "class_id": 2 }, { "student_id": 1, "class_id": 1 },
structure:
package studentclass type studentclasses struct { studentclasses []studentclass } type studentclass struct { studentid int `json:"student_id"` classid int `json:"class_id"` }
My functions:
func Read() { var studentClasses studentClass.StudentClasses jsonFile, err := os.Open("db/student_class.json") if err != nil { fmt.Println(err) } defer jsonFile.Close() byteValue, _ := io.ReadAll(jsonFile) json.Unmarshal(byteValue, &studentClasses) for i := 0; i < len(studentClasses.StudentClasses); i++ { fmt.Println(studentClasses.StudentClasses[i]) } }
Nothing returned
When I add fmt.println(studentclasses)
after json.unmarshall...
it returns {[]}
json.unmarshal error is zero
I have researched this problem, but people who have the same problem as me said that the fields of the structure are not exported. Example: go json.unmarshal doesn't work I don't know where the error is and what I did wrong Please help me solve this problem. thank you all!
You did not specify the json name of studentclasses.
type studentclasses struct { studentclasses []studentclass `json:"student_class"` }
Example:
package main import ( "encoding/json" "fmt" ) type StudentClasses struct { StudentClasses []StudentClass `json:"student_class,omitempty"` } type StudentClass struct { StudentId int `json:"student_id"` ClassId int `json:"class_id"` } func main() { _json := `{ "student_class": [ { "student_id": 1, "class_id": 2 }, { "student_id": 1, "class_id": 1 } ] }` var studentClasses StudentClasses json.Unmarshal([]byte(_json), &studentClasses) fmt.Printf("%+v", studentClasses) }
The above is the detailed content of json.Unmarshal doesn't work even with exported fields. For more information, please follow other related articles on the PHP Chinese website!