Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Decoding JSON int into string

Tags:

go

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

like image 958
Shiki Avatar asked Jun 29 '14 22:06

Shiki


People also ask

How to convert in JSON format?

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.

What is JSON Unmarshal?

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.

How do I use Unmarshal JSON?

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.


1 Answers

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

like image 66
Simon Whitehead Avatar answered Sep 20 '22 12:09

Simon Whitehead