登录
首页 >  Golang >  Go问答

Golang - 解析复杂的嵌套 JSON 数据

来源:stackoverflow

时间:2024-02-22 23:51:26 143浏览 收藏

小伙伴们对Golang编程感兴趣吗?是否正在学习相关知识点?如果是,那么本文《Golang - 解析复杂的嵌套 JSON 数据》,就很适合你,本篇文章讲解的知识点主要包括。在之后的文章中也会多多分享相关知识点,希望对大家的知识积累有所帮助!

问题内容

我有一个如下所示的 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这种结构?


解决方案


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

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 构造 locations

您需要更精确地解组到的结构。根据官方 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

文中关于的知识介绍,希望对你的学习有所帮助!若是受益匪浅,那就动动鼠标收藏这篇《Golang - 解析复杂的嵌套 JSON 数据》文章吧,也可关注golang学习网公众号了解相关技术文章。

声明:本文转载于:stackoverflow 如有侵犯,请联系study_golang@163.com删除
相关阅读
更多>
最新阅读
更多>
课程推荐
更多>