Last active
June 25, 2018 07:50
-
-
Save jastisriradheshyam/a96712051f11c36b2a2f3f90d0c05da6 to your computer and use it in GitHub Desktop.
This is to get the unknown data (from json) and parse in go program for further opertions
This file contains 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 | |
// Importing libraries | |
import ( | |
"encoding/json" | |
"fmt" | |
) | |
func main() { | |
// Sample JSON string | |
s := `{"url": "http://static01.nyt.com/images/2015/12/27/nyregion/27CHRISTIE1/27CHRISTIE1-thumbStandard.jpg", | |
"format": "Standard Thumbnail", | |
"height": 75, | |
"width": 75, | |
"type": "image", | |
"subtype": "photo", | |
"caption": "Gov. Chris Christie of New Jersey spoke about the Sept. 11, 2001, attacks at a Republican conference last month.", | |
"copyright": "Stephen Crowley/The New York Times" | |
}` | |
// interface variable | |
var someStruct interface{} | |
// Unmarshalling the JSON into interface | |
err := json.Unmarshal([]byte(s), &someStruct) | |
if err != nil { | |
fmt.Println("err") | |
} | |
// Converting into pure map (type asserting) | |
someStructMap, ok := someStruct.(map[string]interface{}) | |
if ok != true { | |
fmt.Println("Map coneversion is unsuccessfull") | |
} | |
// Printing the desired key value pair. | |
fmt.Println(someStructMap["caption"]) | |
var someNum float64 | |
// type asserting the interface as float64 | |
someInt = somestructMap["height"].(float64) | |
fmt.Println(someNum) | |
} |
if there is a array in the json then use
someJSONArray, ok := someJSON.([]interface{})
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
References:
[1] go - Getting invalid operation: mymap["title"] (type interface {} does not support indexing) when trying to index a map - Stack Overflow (https://stackoverflow.com/questions/25214036/getting-invalid-operation-mymaptitle-type-interface-does-not-support-in)