如何解组数组内的对象

huangapple go评论74阅读模式
英文:

How to unmarshal objects inside array

问题

我正在尝试访问数组中对象的值。

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

我使用以下代码进行解组:

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)
}

这是我的结构体:

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

稍后,我只需要使用fmt.Println(data.Lat, data.Lon)即可。

英文:

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.

答案1

得分: 1

你提供的代码应该可以成功解析JSON;问题出在你尝试使用结果的方式上。你说你想使用fmt.Println(data.Lat, data.Lon),但这样是行不通的,因为data是一个切片([]ResponseData),而不是ResponseData。你可以使用fmt.Println(data[0].Lat, data[0].Lon)(在检查元素数量后!),或者遍历元素。

下面的代码可能对你的实验有所帮助(playground - 这里包含比下面更多的内容):

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)
	}
}
英文:

The code you presented should unmarshal your JSON successfully; 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. You could use fmt.Println(data[0].Lat, data[0].Lon) (after checking the number of elements!) or iterate through the elements.

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)
	}
}

huangapple
  • 本文由 发表于 2022年8月6日 07:49:54
  • 转载请务必保留本文链接:https://go.coder-hub.com/73256220.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定