dounan9070 2017-08-23 15:07
浏览 185
已采纳

在Go中解析带有数组的JSON文件

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)
  • 写回答

2条回答 默认 最新

  • donglian4770 2017-08-23 15:20
    关注

    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

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥60 求一个简单的网页(标签-安全|关键词-上传)
  • ¥35 lstm时间序列共享单车预测,loss值优化,参数优化算法
  • ¥15 基于卷积神经网络的声纹识别
  • ¥15 Python中的request,如何使用ssr节点,通过代理requests网页。本人在泰国,需要用大陆ip才能玩网页游戏,合法合规。
  • ¥100 为什么这个恒流源电路不能恒流?
  • ¥15 有偿求跨组件数据流路径图
  • ¥15 写一个方法checkPerson,入参实体类Person,出参布尔值
  • ¥15 我想咨询一下路面纹理三维点云数据处理的一些问题,上传的坐标文件里是怎么对无序点进行编号的,以及xy坐标在处理的时候是进行整体模型分片处理的吗
  • ¥15 CSAPPattacklab
  • ¥15 一直显示正在等待HID—ISP