Skip to content

Instantly share code, notes, and snippets.

@saiumesh535
Created June 11, 2021 10:46
Show Gist options
  • Save saiumesh535/699125625c49d42732479f194c2f8f1e to your computer and use it in GitHub Desktop.
Save saiumesh535/699125625c49d42732479f194c2f8f1e to your computer and use it in GitHub Desktop.
Golang JSON
package main
import (
"encoding/json"
"fmt"
"log"
"github.com/tidwall/gjson"
)
type JsonMap map[string]string
type JsonStruct struct {
Name string `json:"name"`
Location string `json:"location"`
Address string `json:"address"`
}
func (jsonStruct *JsonStruct) updateName(name string) {
jsonStruct.Name = name
}
func merge(a, b interface{}) (interface{}, error) {
ja, err := json.Marshal(b)
if err != nil {
return nil, err
}
err = json.Unmarshal(ja, &b)
if err != nil {
return nil, err
}
return b, nil
}
func main() {
jsonStr := `{"name": "sai", "location": "bhainsa"}`
jsonStrNested := `{"name": "sai", "location": "bhainsa", "nested": { "one": "1", "two": 2 }}`
jsonMap := make(JsonMap)
// convert this into map using default json
if err := json.Unmarshal([]byte(jsonStr), &jsonMap); err != nil {
log.Fatal(err.Error())
}
fmt.Println("name is", jsonMap["name"])
// convert json string into struct
jsonStruct := &JsonStruct{}
if err := json.Unmarshal([]byte(jsonStr), jsonStruct); err != nil {
log.Fatal(err.Error())
}
fmt.Println("name is", jsonStruct.Name)
jsonStruct.updateName("Sai Umesh")
fmt.Println("name is", jsonStruct.Name)
result := gjson.Get(jsonStr, "name")
fmt.Println("result", result.String())
// nested json
resultNested := gjson.Get(jsonStrNested, "nested.one")
fmt.Println("nested ", resultNested.String())
// iterate through json
gjson.Parse(jsonStrNested).ForEach(func(key, value gjson.Result) bool {
fmt.Println("key, value", key.String(), value.String())
return true
})
// merge two structs
one := JsonStruct{
Name: "sai",
Location: "Hyderabad",
}
two := JsonStruct{
Name: "sai",
Location: "Bangalore",
Address: "sasasasas",
}
combine, err := merge(&one, &two)
if err != nil {
log.Fatal(err.Error())
}
fmt.Println(combine)
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment