Home > Mobile >  How to Unmarshal value into json struct of type map[string][int] [closed]
How to Unmarshal value into json struct of type map[string][int] [closed]

Time:09-25

After doing ioutil.ReadAll on a resp.body of some API ,I'm getting:-

[91 34 123 92 34 78 111 79 102 86 105 101 119 115 92 34 58 123 92 34 48 92 34 58 48 125 44 92 34 78 111 79 102 76 105 107 101 115 92 34 58 123 92 34 48 92 34 58 48 125 44 92 34 78 111 79 102 67 111 109 109 101 110 116 115 92 34 58 123 92 34 48 92 34 58 48 125 44 92 34 78 111 79 102 83 104 97 114 101 115 92 34 58 123 92 34 48 92 34 58 48 125 125 34 44 34 123 125 34 93 10]

Now I've to unmarshal this to a struct json of type =

type ActUser struct {
    NoOfViews    map[string]int `json:"NoOfViews,omitempty"`
    NoOfLikes    map[string]int `json:"NoOfLikes,omitempty"`
    NoOfComments map[string]int `json:"NoOfComments,omitempty"`
    NoOfShares   map[string]int `json:"NoOfShares,omitempty"`
}

But when I do

var try []ActUser
err = json.Unmarshal(bodyBytes, &try)

I'm getting error := cannot unmarshal string into Go value of type model.ActUser

I tried converting,but nothing seems to work.

CodePudding user response:

Your example JSON data [91 34 123 ... corresponds to ["{.

This indicates the JSON you are receiving is probably invalid -- it's an array of strings, not an array of objects. It looks like your object is probably getting quoted when it is marshalled.

It can be unmarshalled into []string, not []ActUser. This is almost certainly undesirable, and a mistake when the source data was encoded. The best approach would be to fix the bug which causes the JSON object to be quoted as a string.

Alternatively, if you must extract data from the buggy JSON, you could:

var strs []string
if err := json.Unmarshal(bodyBytes, &strs); err != nil {
  log.Fatal(err)
}

if len(strs) == 0 {
  log.Fatal("missing ActUser object")
}

var user ActUser
if err := json.Unmarshal([]byte(strs[0]), &user); err != nil {
  log.Fatal(err)
}

Separately, I'd recommend using fmt.Printf("%s\n", bodyBytes) to display your raw JSON data for debugging (much easier than a list of ASCII codes).

  • Related