Wednesday, 15 May 2019

Go: Unmarshal generic json


By unmarshalling json to 'map[string]interface{}' you can work with generic json.

For example, json string {"FirstName":"Krishna","LastName":"Gurram","ID":123} is equivalant to given byte array.
{123, 34, 70, 105, 114, 115, 116, 78, 97, 109, 101, 34, 58, 34, 75, 114, 105, 115, 104, 110, 97, 34, 44, 34, 76, 97, 115, 116, 78, 97, 109, 101, 34, 58, 34, 71, 117, 114, 114, 97, 109, 34, 44, 34, 73, 68, 34, 58, 49, 50, 51, 125}

Step 1: Define byte array
byteArray := []byte{123, 34, 70, 105, 114, 115, 116, 78, 97, 109, 101, 34, 58, 34, 75, 114, 105, 115, 104, 110, 97, 34, 44, 34, 76, 97, 115, 116, 78, 97, 109, 101, 34, 58, 34, 71, 117, 114, 114, 97, 109, 34, 44, 34, 73, 68, 34, 58, 49, 50, 51, 125}

Step 2: Unmarshal byteArray to generic map
var anyJSON map[string]interface{}
err := json.Unmarshal(byteArray, &anyJSON)

Step 3: You can access the data with below statements.
firstName := anyJSON["FirstName"].(string)
lastName := anyJSON["LastName"].(string)
ID := int(anyJSON["ID"].(float64))

Find the below working application.

App.go
package main

import (
 "encoding/json"
 "fmt"
)

func main() {

 //Step 1: Define byte array
 byteArray := []byte{123, 34, 70, 105, 114, 115, 116, 78, 97, 109, 101, 34, 58, 34, 75, 114, 105, 115, 104, 110, 97, 34, 44, 34, 76, 97, 115, 116, 78, 97, 109, 101, 34, 58, 34, 71, 117, 114, 114, 97, 109, 34, 44, 34, 73, 68, 34, 58, 49, 50, 51, 125}

 //Step 2: Unmarshal byteArray to generic map
 var anyJSON map[string]interface{}
 err := json.Unmarshal(byteArray, &anyJSON)

 if err != nil {
  fmt.Println("Can;t unmarshal the byte array")
  return
 }

 firstName := anyJSON["FirstName"].(string)
 lastName := anyJSON["LastName"].(string)
 ID := int(anyJSON["ID"].(float64))

 fmt.Println(anyJSON)
 fmt.Println("FirstName : ", firstName)
 fmt.Println("LastName : ", lastName)
 fmt.Println("ID: ", ID)

}

Output
map[FirstName:Krishna LastName:Gurram ID:123]
FirstName :  Krishna
LastName :  Gurram
ID:  123



Previous                                                 Next                                                 Home

No comments:

Post a Comment