从JSON解析对象的嵌套数组到Go

I've looked through many examples of how to parse JSON using go and I understand the basics. But I cannot get an array of objects to parse properly. I have created a struct for the object but no dice!

Here's a playground about it: playground

package main

import (
    "encoding/json"
    "fmt"
)

type Outer struct {
    Number  int      `json: "number"`
    Message string   `json: "message"`
    Person  []Person `json: "person"`
}

type Person struct {
    craft string `json: "craft"`
    name  string `json: "name"`
    }

func main() {
    text := `{"people": [{"craft": "ISS", "name": "Sergey Rizhikov"}, {"craft": "ISS", "name": "Andrey Borisenko"}, {"craft": "ISS", "name": "Shane Kimbrough"}, {"craft": "ISS", "name": "Oleg Novitskiy"}, {"craft": "ISS", "name": "Thomas Pesquet"}, {"craft": "ISS", "name": "Peggy Whitson"}], "message": "success", "number": 6}`

    textBytes := []byte(text)


    people1 := Outer{}

    err := json.Unmarshal(textBytes, &people1)
    if err != nil {
        fmt.Println(err)
        return
    }

    fmt.Println(people1)
}

You have several mistakes in your code:

  1. You have people field in the json but person in the struct declaration.
  2. In the Person struct fields must start with upper letter.
  3. Remove whitespace in the json tag json:"name" valid while json: "name" is invalid.

Here is the fixed version.

Updated code with issues fix:

package main

import (
    "encoding/json"
    "fmt"
)

type Outer struct {
    Number  int      `json:"number"`
    Message string   `json:"message"`
    Person  []Person `json:"person"`
}

type Person struct {
    Craft string `json:"craft"`
    Name  string `json:"name"`
}

func main() {
    text := `{"person": [{"craft": "ISS", "name": "Sergey Rizhikov"}, {"craft": "ISS", "name": "Andrey Borisenko"}, {"craft": "ISS", "name": "Shane Kimbrough"}, {"craft": "ISS", "name": "Oleg Novitskiy"}, {"craft": "ISS", "name": "Thomas Pesquet"}, {"craft": "ISS", "name": "Peggy Whitson"}], "message": "success", "number": 6}`

    textBytes := []byte(text)

    people1 := Outer{}

    err := json.Unmarshal(textBytes, &people1)
    if err != nil {
        fmt.Println(err)
        return
    }

    b, err := json.Marshal(people1)
    if err != nil {
        fmt.Println("marshalling error")
        return
    }
    fmt.Println("Data : ", string(b))
}

Output:

Data :  {"number":6,"message":"success","person":[{"craft":"ISS","name":"Sergey Rizhikov"},{"craft":"ISS","name":"Andrey Borisenko"},{"craft":"ISS","name":"Shane Kimbrough"},{"craft":"ISS","name":"Oleg Novitskiy"},{"craft":"ISS","name":"Thomas Pesquet"},{"craft":"ISS","name":"Peggy Whitson"}]}

Check in playground: https://play.golang.org/p/tdNpgUAOLVF