英文:
How can I convert a string to JSON and save the data in an array?
问题
我正在使用这个JSON解析器从API获取的JSON响应中提取数据。它返回一个包含数据的字节数组,当我将字节数组转换为字符串并打印时,我得到以下输出:
[{"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"}]
由于这是一个普通的字符串,我无法对数据进行操作以提取我需要的内容。理想情况下,我想要得到这样的数组:
shows := ["Vikings", "Spartacus: Gods Of The Arena", ...]
movies := ["Se7en", "other data", ...]
我想要做的是根据用户请求的类型(例如:show、movie等)给用户提供标题。因此,我正在寻找一种将字符串转换为可以轻松操作(并可能过滤)的方法。
如果这种方法看起来很奇怪,我向你道歉,但我想不出其他的方法。我觉得Go的语法和做事方式与像JavaScript这样的其他语言非常不同,在JavaScript中,我可以轻松地用一两行代码完成这个任务。
英文:
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
得分: 2
使用标准的encoding/json包将数据解组为与数据形状匹配的值:
var items []struct { // 使用切片表示JSON数组,使用结构体表示JSON对象
Name string
Type string
}
if err := json.Unmarshal(d, &items); err != nil {
log.Fatal(err)
}
遍历解组后的项以查找节目和电影:
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)
}
}
英文:
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)
}
}
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论