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

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

报告相同问题?

悬赏问题

  • ¥50 有数据,怎么建立模型求影响全要素生产率的因素
  • ¥50 有数据,怎么用matlab求全要素生产率
  • ¥15 TI的insta-spin例程
  • ¥15 完成下列问题完成下列问题
  • ¥15 C#算法问题, 不知道怎么处理这个数据的转换
  • ¥15 YoloV5 第三方库的版本对照问题
  • ¥15 请完成下列相关问题!
  • ¥15 drone 推送镜像时候 purge: true 推送完毕后没有删除对应的镜像,手动拷贝到服务器执行结果正确在样才能让指令自动执行成功删除对应镜像,如何解决?
  • ¥15 求daily translation(DT)偏差订正方法的代码
  • ¥15 js调用html页面需要隐藏某个按钮