I have this simple JSON string where I want user_id
to be converted into string when doing json.Unmarshal
:
{"user_id": 344, "user_name": "shiki"}
I have tried this:
type User struct { Id string `json:"user_id,int"` Username string `json:"user_name"` } func main() { input := `{"user_id": 344, "user_name": "shiki"}` user := User{} err := json.Unmarshal([]byte(input), &user) if err != nil { panic(err) } fmt.Println(user) }
But I just get this error:
panic: json: cannot unmarshal number into Go value of type string
Playground link: http://play.golang.org/p/mAhKYiPDt0
String data can be easily converted to JSON using the stringify() function, and also it can be done using eval() , which accepts the JavaScript expression that you will learn about in this guide.
To unmarshal a JSON array into a slice, Unmarshal resets the slice length to zero and then appends each element to the slice. As a special case, to unmarshal an empty JSON array into a slice, Unmarshal replaces the slice with a new empty slice.
To parse JSON, we use the Unmarshal() function in package encoding/json to unpack or decode the data from JSON to a struct. Unmarshal parses the JSON-encoded data and stores the result in the value pointed to by v. Note: If v is nil or not a pointer, Unmarshal returns an InvalidUnmarshalError.
You can use the type json.Number
which is implemented as a string
:
type User struct { Id json.Number `json:"user_id"` Username string `json:"user_name"` }
Then you can simply convert it in any other code:
stringNumber := string(userInstance.Id)
Playground: https://play.golang.org/p/2BTtWKkt8ai
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With