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?
We will use interface for the dynamic key.
For example the json value be like:
{
"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
}
}
}
The “TRPV6” key is the one which is constantly changed.
To get the key from the interface:
func Keys(m map[string]interface{}) []string {
keys := make([]string, len(m))
i := 0
for k := range m {
keys[i] = k
i++
}
return keys
}
Running the Keys method will show the key of interface like
[OR4F5]
If we don’t want it to be so generic, we can apply the specific object type:
- UnMarshal
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
}
- Keys
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]
}
The test code will be implemented like
line := scanner.Text()
listJsonEnsembl = append(listJsonEnsembl, line)
geneResult := gene.ResultObject{}
result := geneResult.UnmarshalJSON([]byte(line))
localKey := Keys(result)
fmt.Println(result[localKey].Ncbi.Name)
Hope it helps~~
PEACE!!!