dave
dave

Reputation: 1173

Unmarshalling JSON string with Golang

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"

Upvotes: 0

Views: 106

Answers (2)

0x4e696b68696c
0x4e696b68696c

Reputation: 169

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

Upvotes: 1

Brits
Brits

Reputation: 18245

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).

Upvotes: 2

Related Questions