Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to convert JSON string to struct

Tags:

json

struct

go

I have start working in golang, I am trying to parse JSON string to struct but its not working.

JSON String:

dailies":[{"userAccessToken":"acessToken","uploadStartTimeInSeconds":1499744832,"uploadEndTimeInSeconds":1499744832,"callbackURL":"callbackurl"}]}

type pingDataFormat struct {
    userAccessToken          string
    uploadStartTimeInSeconds int
    uploadEndTimeInSeconds   int
    callbackURL              string 
}

Below is code which convert JSON String to structs

pingJSON := make(map[string][]pingDataFormat)

err := json.Unmarshal([]byte(pingData), &pingJSON)

if err != nil {
    panic(err)
}

fmt.Printf("\n\n json object:::: %v", pingJSON)

output is:

json object:::: map[dailies:[{ 0 0 }]]

Here "dailies" dont have data, So do i following right approach to parse and how to get data after parse?

like image 411
nadim Avatar asked Jul 29 '17 07:07

nadim


1 Answers

The fields in pingDataFormat need to be exported (start with a capital letter)

type pingDataFormat struct {
    UserAccessToken          string `json:"userAccessToken"`
    UploadStartTimeInSeconds int    `json:"uploadStartTimeInSeconds"`
    UploadEndTimeInSeconds   int    `json:"uploadEndTimeInSeconds"`
    CallbackURL              string `json:"callbackURL"`
}

That should solve your problem

https://play.golang.org/p/Z3yszFl01L

like image 59
sberry Avatar answered Sep 28 '22 13:09

sberry