Skip to content

Instantly share code, notes, and snippets.

@jastisriradheshyam
Last active June 25, 2018 07:50
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save jastisriradheshyam/a96712051f11c36b2a2f3f90d0c05da6 to your computer and use it in GitHub Desktop.
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
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)
}
@jastisriradheshyam
Copy link
Author

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)

@jastisriradheshyam
Copy link
Author

if there is a array in the json then use
someJSONArray, ok := someJSON.([]interface{})

Example:
https://play.golang.org/p/BHEYbsKAcpP

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment