duansaoguan7955 2016-11-11 13:03
浏览 70
已采纳

如何将字符串转换为JSON并将数据保存在数组中?

I'm using this JSON parser to extract data from a JSON response I'm getting from an API. It returns a byte array containing the data and when convert the byte array to a string and print it, I get the following output:

   [{"Name": "Vikings", "Type": "show"}, 
   {"Name": "Spartacus: Gods Of The Arena", "Type": "show"}, 
   {"Name": "True Detective", "Type": "show"}, 
   {"Name": "The Borgias", "Type": "show"}, 
   {"Name": "Se7en", "Type": "movie"}]

Since this is a regular string, I have no way of maniuplating the data to extract whatever I need. Ideally, I'd like to have arrays like these:

   shows := ["Vikings", "Spartacus: Gods Of The Arena"...]
   movies := ["Se7en", "other data", ...]

What I want to do with these arrays is give the user titles based on the type (ie: show, movie, etc) he/she asked for. So essentially what I'm looking for is a way to convert the string in to something that I can easily manipulate (and possibly filter).

I apoligize if this seems like a strange way of doing this, but I can't think of any other way of doing it. I feel like Go's syntax and way of doing things is very unconventional compared to another language like Javascript where I could easily have done this in a line or two.

  • 写回答

1条回答 默认 最新

  • doudao9896 2016-11-11 15:40
    关注

    Use the standard encoding/json package to unmarshal the data into a value matching the shape of the data:

    var items []struct {  // Use slice for JSON array, struct for JSON object
        Name string       
        Type string        
    }
    if err := json.Unmarshal(d, &items); err != nil {
        log.Fatal(err)
    }
    

    Loop through the unmarshaled items to find shows and movies:

    var shows, movies []string
    for _, item := range items {
        switch item.Type {
        case "movie":
            movies = append(movies, item.Name)
        case "show":
            shows = append(shows, item.Name)
        }
    }
    

    playground example

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥20 易康econgnition精度验证
  • ¥15 线程问题判断多次进入
  • ¥15 msix packaging tool打包问题
  • ¥28 微信小程序开发页面布局没问题,真机调试的时候页面布局就乱了
  • ¥15 python的qt5界面
  • ¥15 无线电能传输系统MATLAB仿真问题
  • ¥50 如何用脚本实现输入法的热键设置
  • ¥20 我想使用一些网络协议或者部分协议也行,主要想实现类似于traceroute的一定步长内的路由拓扑功能
  • ¥30 深度学习,前后端连接
  • ¥15 孟德尔随机化结果不一致