douyu3145 2019-02-10 22:41
浏览 150

解析嵌套的JSON字符串

I am trying to parse a nested json string

I did get it to work by using multiple structs, but I am wondering if I can parse the JSON without using an extra struct.

type Events struct {
    Events []Event `json:"events"`
}

type Event struct {
    Name    string  `json:"name"`
    Url     string  `json:"url"`
    Dates   struct {
        Start   struct {
            LocalDate   string 
            LocalTime   string
        }
    }
}

type Embed struct {
    TM Events `json:"_embedded"`
}

func TMGetEventsByCategory(location string, category string) {
    parameters := "city=" + location + "&classificationName=" + category + "&apikey=" + api_key
    tmUrl := tmBaseUrl + parameters
    resp, err := http.Get(tmUrl)
    var embed Embed
    var tm Event
    if err != nil {
        log.Printf("The HTTP request failed with error %s
", err)
    } else {
        data, _ := ioutil.ReadAll(resp.Body)

        err := json.Unmarshal(data, &embed)
        json.Unmarshal(data, &tm)

    }
}

JSON Data looks like this:

{
  "_embedded": { 
     "events": [],
  },
  "OtherStuff": {
  }
}

Is it possible to get rid of the Embed struct and read straight to the events part of the json string?

  • 写回答

2条回答 默认 最新

  • duanjian3338 2019-02-11 13:29
    关注

    What you're looking for here is json.RawMessage. It can help delay parsing of certain values, and in you case map[string]json.RawMessage should represent the top-level object where you can selectively parse values. Here's a simplified example you can adjust to your case:

    package main
    
    import (
        "encoding/json"
        "fmt"
    )
    
    type Event struct {
        Name string `json:"name"`
        Url  string `json:"url"`
    }
    
    func main() {
        bb := []byte(`
        {
            "event": {"name": "joe", "url": "event://101"},
            "otherstuff": 15.2,
            "anotherstuff": 100
        }`)
    
        var m map[string]json.RawMessage
        if err := json.Unmarshal(bb, &m); err != nil {
            panic(err)
        }
    
        if eventRaw, ok := m["event"]; ok {
            var event Event
            if err := json.Unmarshal(eventRaw, &event); err != nil {
                panic(err)
            }
            fmt.Println("Parsed Event:", event)
        } else {
            fmt.Println("Can't find 'event' key in JSON")
        }
    }
    

    In your case look for the _embedded key and then Unmarshal its value to Events

    评论

报告相同问题?

悬赏问题

  • ¥15 python的qt5界面
  • ¥15 无线电能传输系统MATLAB仿真问题
  • ¥50 如何用脚本实现输入法的热键设置
  • ¥20 我想使用一些网络协议或者部分协议也行,主要想实现类似于traceroute的一定步长内的路由拓扑功能
  • ¥30 深度学习,前后端连接
  • ¥15 孟德尔随机化结果不一致
  • ¥15 apm2.8飞控罗盘bad health,加速度计校准失败
  • ¥15 求解O-S方程的特征值问题给出边界层布拉休斯平行流的中性曲线
  • ¥15 谁有desed数据集呀
  • ¥20 手写数字识别运行c仿真时,程序报错错误代码sim211-100