Golang-解析嵌套的json值

时间:2020-04-27 22:06:20

标签: json go

我有一个像这样的json数据:

    [
      {
        lat: "41.189301799999996",
        lon: "11.918255998031015",
        display_name: "Some place",
        address: {
          address: "Address",
          country: "Country",
          country_code: "CC"
        },
        geojson: {
          type: "Polygon",
          coordinates: [
             [
               [14.4899021,41.4867039],
               [14.5899021,41.5867039],
             ]
          ]
        }
     }
   ]

我想解析此数据,从该数组中获取第一个元素,并将其转换为新的结构,如下所示:

type Location struct {
    Name        string
    Country     string
    CountryCode string
    Center      Coordinate
    Coordinates []Coordinate
}

我已经定义了这样的坐标类型:

type Coordinate struct {
    Lat string `json:"lat"`
    Lng string `json:"lon"`
}

但是,如果尝试这样解析:

bytes, err := ioutil.ReadAll(res.Body)

if err != nil {
    http.Error(w, err.Error(), http.StatusBadRequest)
}

var locations [0]Location

if err := json.Unmarshal(bytes, &locations); err != nil {
    fmt.Println("Error parsing json", err)
}

fmt.Println(locations)

但是,这让我在终端机上了

[{   { } []}]

我如何解析这种json结构并将其转换为location这种结构?

2 个答案:

答案 0 :(得分:1)

您应该使用与输入文档匹配的结构来解组:

type Entry struct {
  Lat string `json:"lat"`
  Lon string `json:"lon"`
  DisplayName string `json:"display_name"`
  Address struct {
      Address string `json:"address"`
      Country string `json:"country"`
      Code string `json:"country_code"`
  } `json:"address"`
  Geo struct {
     Type string `json:"type"`
     Coordinates [][][]float64 `json:"coordinates"`
  } `json:"geojson"`
}

然后解组到一个Entry数组:

var entries []Entry
json.Unmarshal(data,&entries)

然后,使用entries来构造Location s

答案 1 :(得分:1)

您需要更精确地解组您的结构。根据官方JSON规范,您还需要在密钥周围加双引号。省略引号仅适用于JavaScript,JSON需要这些引号。

最后一件事,我知道这很愚蠢,但是最后一个内部数组之后的最后一个逗号也是无效的,必须删除它:

package main

import (
    "encoding/json"
    "fmt"
)

type Location struct {
    Lat         string     `json:"lat"`
    Lng         string     `json:"lon"`
    DisplayName string     `json:"display_name"`
    Address     Address    `json:"address"`
    GeoJSON     Geo        `json:"geojson"`
}

type Address struct {
    Address     string `json:"address"`
    Country     string `json:"country"`
    CountryCode string `json:"country_code"`
}

type Geo struct {
    Type        string         `json:"type"`
    Coordinates [][]Coordinate `json:"coordinates"`
}

type Coordinate [2]float64

func main() {
    inputJSON := `
    [
          {
            "lat": "41.189301799999996",
            "lon": "11.918255998031015",
            "display_name": "Some place",
            "address": {
              "address": "123 Main St.",
              "country": "USA",
              "country_code": "+1"
            },
            "geojson": {
              "type": "Polygon",
              "coordinates": [
                [
                  [14.4899021,41.4867039],
                  [14.5899021,41.5867039]
                ]
              ]
            }
          }
        ]`

    var locations []Location

    if err := json.Unmarshal([]byte(inputJSON), &locations); err != nil {
        panic(err)
    }

    fmt.Printf("%#v\n", locations)
}

您也可以run this on the Go Playground