Swailem95 Swailem95 - 26 days ago 6
JSON Question

How can I convert a string to JSON and save the data in an array?

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.

Answer

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