Home > Software engineering >  Unmarshalling JSON string with Golang
Unmarshalling JSON string with Golang

Time:09-09

I have the following json string

{"x":{"l.a":"test"}}

type Object struct {
    Foo  map[string]map[string]string `json:"l.a"`
    }
     var obj Object
    err = json.Unmarshal(body, &obj)
    if err != nil{
        fmt.Println(err)
    }
    fmt.Println("jsonObj", obj)

but get empty any idea how can i get the string "test"

CodePudding user response:

With your code Unmarshal is looking for l.a at the top level in the JSON (and it's not there - x is).

There are a number of ways you can fix this, the best is going to depend upon your end goal; here are a couple of them (playground)

const jsonTest = `{"x":{"l.a":"test"}}`

type Object struct {
    Foo map[string]string `json:"x"`
}

func main() {
    var obj Object
    err := json.Unmarshal([]byte(jsonTest), &obj)
    if err != nil {
        fmt.Println(err)
    }
    fmt.Println("jsonObj", obj)

    var full map[string]map[string]string
    err = json.Unmarshal([]byte(jsonTest), &full)
    if err != nil {
        fmt.Println(err)
    }
    fmt.Println("jsonObj2", full)

}

(Got a phone call while entering this and see @DavidLilue has provided a similar comment but may as well post this).

CodePudding user response:

You can always create a struct to unmarshall your json

type My_struct struct {
    X struct {
        LA string `json:"l.a"`
    } `json:"x"`
}

func main() {
    my_json := `{"x":{"l.a":"test"}}`
    var obj My_struct
    json.Unmarshal([]byte(my_json), &obj)
    fmt.Println(obj.X.LA)
}

here you are creating a struct and then unmarshalling your json string to its object, so when you do obj.X.LA you will get the string

  •  Tags:  
  • go
  • Related