如何解析字符串以进行结构化并写入文件

I want to parse the schools array in the string and and want to write in a file by using golang. lets assume i have a string which is called as data;

{
    "name": "alex",
    "schools": [
        {"location": "xxx" , "year": 2012},
        {"location": "xxx" , "year": 2012},
    ]
}

I want to parse it and write schools to a file.

In order to achive it. I first write a struct as;

type User struct{
    name string `json:"name"`
    Schools []struct {
        Location string
        Year    int
    }
} 

then create a variable and try to parse the string as,

var u User
err := json.Unmarshal([]byte(data), &u)


_, err = createdFile.Write(u.Schools)

But this give me error as

cannot use m (type User) as type []byte in argument to createdFile.Write

How can I do it? Where is my mistake?

I found the following two problems:

  1. You've passed u.Schools of type []struct { Location string Year int } instead of a []byte
  2. Also your json data is still not valid.

So here is my solution. Since you didn't provide the createdFile.Write() details, I used here ioutil package.

package main

import (
    "encoding/json"
    "fmt"
    "io/ioutil"
    "log"
)

var data = `{
    "name": "alex",
    "schools": [
        {"location": "xxx" , "year": 2012},
        {"location": "xxx" , "year": 2012}
    ]
}`

type User struct {
    Name    string `json:"name"`
    Schools []struct {
        Location string
        Year     int
    }
}

func main() {
    var (
        u User
        err error
        schoolsBytes []byte
    )

    if err = json.Unmarshal([]byte(data), &u); err != nil {
        log.Fatalln(err)
    }
    fmt.Println(u.Schools)

    schoolsBytes, err = json.Marshal(u.Schools)
    if err != nil {
        log.Fatalln(err)
    }

    err = ioutil.WriteFile("/tmp/dat1", schoolsBytes, 0777)
    if err != nil {
        log.Fatalln(err)
    }

    dat, err := ioutil.ReadFile("/tmp/dat1")
    if err != nil {
        log.Fatalln(err)
    }
    fmt.Print(string(dat))
}