使用Go解析带有数组的JSON文件。

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

Parsing JSON files with arrays in Go

问题

以下是我试图解析的JSON文件(如果有人感兴趣,这是OpenWeatherMap API)。内置的encoding/json在这方面做得相当不错。当我使用json.Unmarshal(testJson, &parsed)时,大部分JSON文件都被正确解析了。然而,由于其格式的原因,"weather"部分让我头疼。

我使用parsedMap := parsed.(map[string]interface{})解析了encoding/json生成的文件,当我尝试引用键值对中的键"main"时,它是有效的。

使用fmt.Println(),值为map[temp:280.32 pressure:1012 humidity:81 temp_min:279.15 temp_max:281.15],我可以处理它。

然而,对于键"weather",我得到了[map[icon:09d id:300 main:Drizzle description:light intensity drizzle]]。额外的方括号似乎引起了问题。

{
  "coord": {
    "lon": -0.13,
    "lat": 51.51
  },
  "weather": [
    {
      "id": 300,
      "main": "Drizzle",
      "description": "light intensity drizzle",
      "icon": "09d"
    }
  ],
  "base": "stations",
  "main": {
    "temp": 280.32,
    "pressure": 1012,
    "humidity": 81,
    "temp_min": 279.15,
    "temp_max": 281.15
  },
  "visibility": 10000,
  "wind": {
    "speed": 4.1,
    "deg": 80
  },
  "clouds": {
    "all": 90
  },
  "dt": 1485789600,
  "sys": {
    "type": 1,
    "id": 5091,
    "message": 0.0103,
    "country": "GB",
    "sunrise": 1485762037,
    "sunset": 1485794875
  },
  "id": 2643743,
  "name": "London",
  "cod": 200
}

参考代码:

var testJSON = //在帖子中的JSON
var parsed interface{}

json.Unmarshal(testJSON, &parsed)

parsedMap := parsed.(map[string]interface{})
mainTemp := parsedMap["weather"]

fmt.Println(mainTemp)
英文:

The following is the JSON file I'm trying to parse (OpenWeatherMap API if anyone is curious). The builtin encoding/json does a pretty good job of it. When I use json.Unmarshal(testJson, &parsed), most of the JSON file is parsed correctly. However, with the way that it is formatted, the "weather" is giving me a headache.

I parsed the file generated by encoding/json with parsedMap := parsed.(map[string]interface{}), which works when I try to refer to key,value pair with the key "main".

With fmt.Println(), the value is map[temp:280.32 pressure:1012 humidity:81 temp_min:279.15 temp_max:281.15], which I can work with.

With the key "weather" however, I get this [map[icon:09d id:300 main:Drizzle description:light intensity drizzle]]. The additional square brackets seem to be causing issues.

{
  "coord": {
      "lon": -0.13,
      "lat": 51.51
    },
    "weather": [
      {
        "id": 300,
        "main": "Drizzle",
        "description": "light intensity drizzle",
        "icon": "09d"
      }
    ],
    "base": "stations",
    "main": {
      "temp": 280.32,
      "pressure": 1012,
      "humidity": 81,
      "temp_min": 279.15,
      "temp_max": 281.15
    },
    "visibility": 10000,
    "wind": {
      "speed": 4.1,
      "deg": 80
    },
    "clouds": {
      "all": 90
    },
    "dt": 1485789600,
    "sys": {
      "type": 1,
      "id": 5091,
      "message": 0.0103,
      "country": "GB",
      "sunrise": 1485762037,
      "sunset": 1485794875
    },
    "id": 2643743,
    "name": "London",
    "cod": 200
  }

Code for reference:

var testJSON = //JSON EARLIER IN THE POST
var parsed interface{}

json.Unmarshal(testJSON, &parsed)

parsedMap := parsed.(map[string]interface{})
mainTemp := parsedMap["weather"]


fmt.Println(mainTemp)

答案1

得分: 1

你应该首先对weather进行类型断言,将其断言为一个interface{}数组。

然后对第一个元素进行相同的类型断言,将其断言为一个map[string]interface{}

示例代码如下:

temps := parsedMap["weather"].([]interface{})
mainTemp := temps[0].(map[string]interface{})

你可以在这里查看完整的示例:https://play.golang.org/p/JIfCGrsYl9

英文:

You should first perform a Type assertions on weather as an array of interface{}.

Then do the same on the first element as a map[string]interface{}

temps := parsedMap["weather"].([]interface{})
mainTemp := temps[0].(map[string]interface{})

You can see a full example here https://play.golang.org/p/JIfCGrsYl9

答案2

得分: 0

问题是你需要将其转换为[]interface{}类型。

然而,你应该使用JSON to Go来轻松生成你期望的JSON的结构体类型。你可以删除你不感兴趣的任何字段。

这样可以节省很多类型转换(和错误检查)!

英文:

The issue is that you need to cast as a []interface{}.

However, you should have a look at using JSON to Go to easily generate a struct type for the JSON you expect. You can strip out any fields you're not interested in.

Saves a lot of type-casting (and error checking)!

huangapple
  • 本文由 发表于 2017年8月23日 23:07:53
  • 转载请务必保留本文链接:https://go.coder-hub.com/45843390.html
匿名

发表评论

匿名网友

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

确定