Home > Mobile >  String Interpolation / Templating Variables in Go lang
String Interpolation / Templating Variables in Go lang

Time:09-06

Let's say I have the following byte string which represents some JSON packet:

data := []byte(`{
    "Id" : 1,
    "Name": "John Doe",
    "Occupation": "gardener"
}`)

I'm wondering, is there a way to create this JSON packet dynamically, e.g.,

var NAME = "John Doe"

var OCCUPATION = "gardener"

data := []byte(`{
    "Id" : 1,
    "Name": {{ NAME }},
    "Occupation": {{ OCCUPATION }}
}`)

CodePudding user response:

You can create a struct and marshal it:

type Data struct {
   ID int `json:"Id"`
   Name string `json:"Name"`
   Occupation string `json:"Occupation"`
}

data:=Data{ ID:1, Name: "name", Occupation: "Occupation" }

byteData, err:=json.Marshal(data)

This will also take care of escaping characters in data when necessary.

Another way:

data:=map[string]interface{} {
  "Id": id,
  "Name": name,
  "Occupation": Occupation,
}
byteData, err:=json.Marshal(data)

You can also use templates for this, but then there is a chance you may generate invalid JSON data if the input strings contain characters that need to be escaped.

CodePudding user response:

Go by Example has a great page on using the encoding/json package: https://gobyexample.com/json

In your specific case:

package main

import (
    "encoding/json"
    "log"
)

type Person struct {
    ID         int    `json:"Id"`
    Name       string `json:"Name"`
    Occupation string `json:"Occupation"`
}

func main() {

    p := Person{ID: 1, Name: "John Doe", Occupation: "gardener"}

    log.Printf("Person data: % v\n", p)

    d, err := json.Marshal(p)
    if err != nil {
        log.Fatalf("failed to marshal json: %v", err)
    }

    log.Printf("Encoded JSON: %s\n", d)
}
2022/09/05 16:02:54 Person data: {ID:1 Name:John Doe Occupation:gardener}
2022/09/05 16:02:54 Encoded JSON: {"Id":1,"Name":"John Doe","Occupation":"gardener"}
  •  Tags:  
  • go
  • Related