3

I'm trying to find the best way to create this JSON object using Go:

{
  "Clients" : [
    {
      "Hostname" : "example.com",
      "IP" : "127.0.0.1",
      "MacAddr" : "mactonight"
    },
    {
      "Hostname" : "foo.biz",
      "IP" : "0.0.0.0",
      "MacAddr" : "12:34:56:78"
    }
  ]
}

In my existing code, I'm currently slicing multiple string lines and then splitting each line into 3 separate variables (host, ip, mac). For example hostname 192.168.1.0 F0:F0:F0:F0:F0 gets converted consectively.

This is done by the following code:

func parselines(line string){
    for _, line := range strings.Split(line, "\n") {
        if line != "" {
            s := strings.Split(line, " ")
            host, ip, mac := s[0], s[1], s[2]
            fmt.Println("Hostname: " + host + " IP: " + ip + " MAC: " + mac)
        }
    }
}

So within this for loop I'd be looking to build the JSON object mentioned above. I've tried with structs but I'm really confused as to how to use them. I've done this with Ruby which took a few lines of code, but Go seems to be quite challenging (for me that is!). In ruby it's done like this:

require 'json'

clients = []

STDIN.each do |line|
  fields = line.split(/\s+/)
  clients << {
    Hostname: fields[0],
    IP: fields[1],
    MacAddr: fields[2]
  }
end

connections = {}
connections[:Clients] = clients
puts connections.to_json
4
  • 1
    Start with gobyexample.com/json Do the simplest thing, like create a structure with a single field Hostname and ensure you can serialise it. Then add 2 more fields. Then turn it into a slice. Then add an external object with Clients. One little step at a time. The important thing here is do one little thing at a time iteratively.
    – zerkms
    Jun 19, 2020 at 22:25
  • Hey man, thanks. I'm going to definitely take your advice on this. I feel like even if I get the solution given to me now, I won't be able to fully understand it. Sometimes a quick reminder like yours is a nice reset to sit back and take it slow. So thanks :) Jun 19, 2020 at 22:34
  • I'd recommend to stay away from that answer. It's not wrong, but it definitely not the "best" way of doing it (it's subjective indeed).
    – zerkms
    Jun 19, 2020 at 22:35
  • I appreciate the heads up! Will try learn more and see if I conform to the idioms myself. Jun 19, 2020 at 22:41

3 Answers 3

7

Declare types that match the structure of the JSON document.

type client struct {
    Hostname string `json:"Hostname"`
    IP       string `json:"IP"`
    MacAddr  string `json:"MacAddr"`
}

type connection struct {
    Clients []*client `json:"Clients"`
}

Initialize values using those types and encode to JSON.

var clients []*client
for _, line := range strings.Split(line, "\n") {
    if line != "" {
        s := strings.Split(line, " ")
        clients = append(clients, &client{Hostname: s[0], IP: s[1], MacAddr: s[2]})
    }
}

p, _ := json.Marshal(connection{Clients: clients})
fmt.Printf("%s\n", p)

The JSON field tags (json:"Hostname") are not needed in this example because the JSON object keys are valid exported identifiers. I include the tags here because they are often needed.

Run the code on the Go Playground.

1
  • This is great, pretty much what I was looking for. I suppose if this was part of a restapi program. Would the connection struct be the response that I would to send back? Jun 20, 2020 at 11:06
3

You need Initialize 2 structs

type Client struct {
    Hostname string
    IP string
    MacAddr string
}

type Connection struct {
    Clients []Client
}

And use Marshal to convert struct to Json

var clients []Client
clients = append(clients, Client{
    Hostname: "localhost",
    IP: "127.0.0.1",
    MacAddr: "1123:22512:25632",
})

// add more if you want ...

myJson, _ := json.Marshal(Connection{Clients:clients})
fmt.Println(string(myJson))

Dont forget import this

import "encoding/json"
1

Create slices and maps to match the structure of the data you want.

var clients []interface{}
for _, line := range strings.Split(line, "\n") {
    if line != "" {
        s := strings.Split(line, " ")
        clients = append(clients, map[string]string{"Hostname": s[0], "IP": s[1], "MAC": s[2]})
    }
}
connections := map[string]interface{}{"Clients": clients}
p, _ := json.Marshal(connections)
fmt.Printf("%s\n", p)
7
  • 2
    What is the point to have []interface{} in a case like this when you have a nice regular structure and may have a stirctly typed code instead?
    – zerkms
    Jun 19, 2020 at 22:29
  • What is the advantage of using strictly typed code here? It will not be faster. It will not prevent bugs.
    – thwd
    Jun 19, 2020 at 22:31
  • Thanks @thwd - out of curiosity most places I've seen usually go down the struct route. I want to know is there any benefit to this way? Again, thanks for your solution :) Jun 19, 2020 at 22:35
  • @Syn it takes fewer lines (at a cost of loose typing). No other benefits really.
    – zerkms
    Jun 19, 2020 at 22:36
  • @zerkms Typed code will make this code more difficult to evolve because one must change both the type and the data. For example, adding a new field to client requires a change to the type and the composite literal initializing the client.
    – thwd
    Jun 19, 2020 at 22:36

Your Answer

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

Not the answer you're looking for? Browse other questions tagged or ask your own question.