0

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 }}
}`)
1
  • 1
    Use fmt.Sprintf after encoding/json.Marshal'ing your strings. Best to avoid such crap and just use encoding/json. Commented Sep 5, 2022 at 15:50

2 Answers 2

3

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.

Sign up to request clarification or add additional context in comments.

2 Comments

Hi Burak, what is the outpout structure of that data? I need the JSON to be in lowercase ...
What part of JSON do you need lowercase? The keys? They change the keys to lowercase. The data? strings.ToLower() the data
0

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"}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.