taeslee
taeslee

Reputation: 31

Unmarshaling string to struct like structure in Golang

I was given a string below with Golang:

var cars = [
    {
       model: "SLR",
       brand: "Mercedes",
       prices: [520, 730],
    },
    {
       model: "M4",
       brand: "BMW",
       prices: [420, 820],
    }
]

I know it is not JSON string. Is there any way at all to "unmarshal" the string and get the models of each car? How can I get the model of each car? or is it a wrong question in the first place? I appreciate your opinion.

Upvotes: 1

Views: 486

Answers (2)

Gopher
Gopher

Reputation: 751

To unmarshal your input and retrieve the model of each car you have to use umarshal method followed by range method,I have reproduced your scenario as follows :

package main

import (
    "fmt"

    "gopkg.in/yaml.v2"
)

type Car struct {
    Model  string `yaml:"model"`
    Brand  string `yaml:"brand"`
    Prices []int  `yaml:"prices"`
}

func main() {
    var car = []byte(`[ { model: "SLR", brand: "Mercedes", prices: [520, 730], }, { model: "M4", brand: "BMW", prices: [420, 820], } ]`)

    var cars []Car
    if err := yaml.Unmarshal(car, &cars); err != nil {
        panic(err)
    }

    for _, v := range cars {
        fmt.Println(v.Model)

    }

} 

Output:

SLR
M4

Upvotes: 4

Daniel
Daniel

Reputation: 1460

You may have luck using yaml for your input:

package main

import (
    "fmt"
    "gopkg.in/yaml.v2"
)

func main() {
    const cars = `[ { model: "SLR", brand: "Mercedes", prices: [520, 730], }, { model: "M4", brand: "BMW", prices: [420, 820], } ]`

    type Car struct {
        Model  string `yaml:"model"`
        Brand  string `yaml:"brand"`
        Prices []int  `yaml:"prices"`
    }

    var carsArr []Car
    if err := yaml.Unmarshal([]byte(cars), &carsArr); err != nil {
        panic(err)
    }

    fmt.Printf("Cars: %+v", carsArr)
    // Cars: [{Model:SLR Brand:Mercedes Prices:[520 730]} {Model:M4 Brand:BMW Prices:[420 820]}]

}

Try it here: https://play.golang.org/p/hRQXSes1tGi

Upvotes: 1

Related Questions