In using Golang, we sometimes need to parse a JSON data without knowing or specifying a concrete type struct. We can do this by converting (json.Unmarshal) JSON data into an interface{}. We can then use it like a map. Accessing it like for example m[“username”].(string)

Below is an example application that converts a JSON string into an interface{}. The statements from line 18 to 23 implements the JSON unmarshall without a concrete struct.

 1package main
 2
 3import (
 4	"encoding/json"
 5	"log"
 6)
 7
 8var sampleJson = `{
 9	"username": "johnpili",
10	"password": "L3akyPa5sw0rd!",
11	"name": "John Pili",
12	"website": "https://johnpili.com",
13	"number": 123
14}`
15
16func main() {
17	rawData := []byte(sampleJson)
18	var payload interface{}                  //The interface where we will save the converted JSON data.
19	err := json.Unmarshal(rawData, &payload) // Convert JSON data into interface{} type
20	if err != nil {
21		log.Fatal(err)
22	}
23	m := payload.(map[string]interface{}) // To use the converted data we will need to convert it into a map[string]interface{}
24
25	log.Printf("Username: %s", m["username"].(string))
26	log.Printf("Password: %s", m["password"].(string))
27	log.Printf("Name: %s", m["name"].(string))
28	log.Printf("Website: %s", m["website"].(string))
29	log.Printf("Number: %d", int(m["number"].(float64)))
30}

Console Output

parse-json-without-struct-console-output.png