Created
November 9, 2015 14:01
-
-
Save jochasinga/f35ca7f599deee82d768 to your computer and use it in GitHub Desktop.
Snippet on how to guess types of data from arbitrary JSON
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
package main | |
import ( | |
"encoding/json" | |
"fmt" | |
"log" | |
) | |
type Hole struct { | |
Alias string `json:"alias"` | |
Id int `json:"id"` | |
Data map[string]interface{} `json:"json_data"` | |
} | |
var j = []byte(`{ | |
"alias": "evergreen-9999", | |
"id": 1, | |
"json_data": { | |
"field_1": "data_1", | |
"field_2": 690, | |
"field_3": [0, "dada", 8.5, {"key": "val"}], | |
"field_4": {"foo": {"bar": "baz"}} | |
} | |
}`) | |
func main() { | |
var hole Hole | |
if err := json.Unmarshal(j, &hole); err != nil { | |
log.Fatal("error:", err) | |
} | |
p := hole.Data | |
for k, v := range p { | |
switch val := v.(type) { | |
case string: | |
fmt.Println(k, v, "is a JSON string") | |
case float64: | |
fmt.Println(k, v, "is a JSON number/float") | |
case bool: | |
fmt.Println(k, v, "is a JSON Boolean") | |
case []interface{}: | |
fmt.Println(k, v, "is a JSON array") | |
for i, v := range val { | |
fmt.Println(i, v) | |
} | |
case map[string]interface{}: | |
fmt.Println(k, v, "is a JSON Value") | |
fmt.Println(v) | |
/* | |
for _k, _v := range v.(map[string]interface{}) { | |
switch _val := _v.(type) { | |
case string: | |
fmt.Println(_k, _v, "STRING") | |
case float64: | |
fmt.Println(_k, _v, "NUM") | |
case bool: | |
fmt.Println(_k, _v, "BOOL") | |
} | |
}*/ | |
default: | |
fmt.Println(k, "is unknown") | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment