简体   繁体   English

如何解组数组内的对象

[英]How to unmarshal objects inside array

I am trying to get access to object's values inside of array我正在尝试访问数组内的对象值

[
  {
    "name": "London",
    "lat": 51.5073219,
    "lon": -0.1276474,
    "country": "GB",
    "state": "England"
  }
]

I use this code to unmarshal it我使用此代码解组它

content, err := ioutil.ReadAll(res.Body)
    if err != nil {
        log.Fatal(err)
    }

    var data []ResponseData
    err = json.Unmarshal(content, &data)
    if err != nil {
        log.Fatal(err)
    }

This is my struct这是我的结构

type ResponseData struct {
    Name       string      `json:"name"`
    Lat        float32     `json:"lat"`
    Lon        float32     `json:"lon"`
    Country    string      `json:"country"`
    State      string      `json:"state"`
}

I need to simply fmt.Println(data.Lat, data.Lon) later.稍后我需要简单地fmt.Println(data.Lat, data.Lon)

The code you presented should unmarshal your JSON successfully;您提供的代码应该成功解组您的 JSON; the issue is with the way you are trying to use the result.问题在于您尝试使用结果的方式。 You say you want to use fmt.Println(data.Lat, data.Lon) but this will not work because data is a slice ( []ResponseData ) not a ResponseData .您说您想使用fmt.Println(data.Lat, data.Lon)但这不起作用,因为data是切片( []ResponseData )而不是ResponseData You could use fmt.Println(data[0].Lat, data[0].Lon) (after checking the number of elements.) or iterate through the elements.您可以使用fmt.Println(data[0].Lat, data[0].Lon) (在检查元素数量之后)或遍历元素。

The below might help you experiment ( playground - this contains a little more content than below):下面可能会帮助您进行实验(游乐场- 这包含比下面更多的内容):

package main

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

const rawJSON = `[
  {
    "name": "London",
    "lat": 51.5073219,
    "lon": -0.1276474,
    "country": "GB",
    "state": "England"
  }
]`

type ResponseData struct {
    Name    string  `json:"name"`
    Lat     float32 `json:"lat"`
    Lon     float32 `json:"lon"`
    Country string  `json:"country"`
    State   string  `json:"state"`
}

func main() {
    var data []ResponseData
    err := json.Unmarshal([]byte(rawJSON), &data)
    if err != nil {
        log.Fatal(err)
    }

    if len(data) == 1 { // Would also work for 2+ but then you are throwing data away...
        fmt.Println("test1", data[0].Lat, data[0].Lon)
    }

    for _, e := range data {
        fmt.Println("test2", e.Lat, e.Lon)
    }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM