0

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"

1
  • 3
    You're defining Foo to look into the l.a property but that property is not present in the root object. Maybe your intention is to have json:"x" as the tag. Also, map[string]map[string]string is redundant, Object acts like the root object so you would need just map[string]string. Commented Sep 9, 2022 at 1:59

2 Answers 2

2

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

Sign up to request clarification or add additional context in comments.

Comments

1

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.