Last active
August 1, 2018 09:51
-
-
Save rodesousa/c0bc0de64599508fac67a0a6c78ae227 to your computer and use it in GitHub Desktop.
json unmarshal #golang
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| type MergeRequests struct { | |
| Title string `json:"title"` | |
| } | |
| func main() { | |
| resp, _ := http.Get("https://gitlab.com/api/v4/projects/4600432/merge_requests?private_token=") | |
| defer resp.Body.Close() | |
| body, _ := ioutil.ReadAll(resp.Body) | |
| var mrs []MergeRequests | |
| json.Unmarshal(body, &mrs) | |
| fmt.Printf("%v", mrs[0].Title) | |
| } | |
| package main | |
| import ( | |
| "encoding/json" | |
| "fmt" | |
| "io/ioutil" | |
| "net/http" | |
| ) | |
| type Project struct { | |
| Name string `json:"name_with_namespace"` | |
| Links map[string]string `json:"_links"` | |
| } | |
| type Resp struct { | |
| Projects []Project `json:"projects"` | |
| } | |
| type Merge struct { | |
| Merge_requests string `json:"merge_requests"` | |
| Self string `json:"self"` | |
| } | |
| func main() { | |
| resp, _ := http.Get("https://gitlab.com/api/v4/groups/1768437?private_token=") | |
| defer resp.Body.Close() | |
| body, _ := ioutil.ReadAll(resp.Body) | |
| res := Resp{} | |
| json.Unmarshal(body, &res) | |
| fmt.Printf("%v", res.Projects[0].Links["merge_requests"]) | |
| } | |
| //read file | |
| func main() { | |
| file, e := ioutil.ReadFile("./config.json") | |
| if e != nil { | |
| fmt.Printf("File error: %v\n", e) | |
| os.Exit(1) | |
| } | |
| fmt.Printf("%s\n", string(file)) | |
| //m := new(Dispatch) | |
| //var m interface{} | |
| var jsontype jsonobject | |
| json.Unmarshal(file, &jsontype) | |
| fmt.Printf("Results: %v\n", jsontype) | |
| } | |
| // best struct | |
| var data = ` | |
| a: Easy! | |
| b: | |
| c: 2 | |
| d: [3, 4] | |
| ` | |
| // Note: struct fields must be public in order for unmarshal to | |
| // correctly populate the data. | |
| type T struct { | |
| A string | |
| B struct { | |
| RenamedC int `yaml:"c"` | |
| D []int `yaml:",flow"` | |
| } | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment