Parse dynamic key in Json in Go

There is time, when we’re not sure what the key_name in json data will be. How do we do it in Go?

Image for post
Image for post
Photo by Paweł Czerwiński on Unsplash
{
"TRPV6": {
"ncbi": {
"symbol": "",
"symbol_source": "",
"id": "",
"gene_name": "",
"gene_synonyms": null,
"biotype": "",
"contig": "",
"start": 0,
"end": 0,
"reference_genome": "",
"strand": "",
"description": ""
},
"ensembl": {
"symbol": "TRPV6",
"symbol_source": "ensembl_havana",
"id": "ENSG00000165125",
"gene_name": "TRPV6",
"gene_synonyms": [
"CaT1",
"ECAC2"
],
"biotype": "",
"contig": "chr7",
"start": 142871208,
"end": 142885745,
"reference_genome": "GRCh38",
"strand": "-",
"description": ""
},
"gene_cards": {
"symbol": "",
"id": "",
"gene_name": "",
"gene_synonyms": null,
"biotype": "",
"contig": "",
"start": 0,
"end": 0,
"reference_genome": "",
"strand": "",
"description": null
}
}
}
func Keys(m map[string]interface{}) []string {
keys := make([]string, len(m))
i := 0
for k := range m {
keys[i] = k
i++
}
return keys
}
[OR4F5]
func (s ResultObject) UnmarshalJSON(data []byte)  map[string]Medium  {
var z map[string]Medium

if err := json.Unmarshal(data, &z); err != nil {
fmt.Println(string(data[:]))
panic(err)
}
return z
}
func Keys(m map[string]gene.Medium) string {
keys := make([]string, len(m))
i := 0
for k := range m {
keys[i] = k
i++
}
return keys[0]
}
line := scanner.Text()
listJsonEnsembl = append(listJsonEnsembl, line)
geneResult := gene.ResultObject{}

result := geneResult.UnmarshalJSON([]byte(line))
localKey := Keys(result)
fmt.Println(result[localKey].Ncbi.Name)

Written by

A passionate automation engineer who strongly believes in “A man can do anything he wants if he puts in the work”.

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store