-1

In perl I can push $hashref into @array and have this data for next foreach and possible encode_json (HTTP POST).

I can't figure out how to recreate the same login in golang?

$VAR1 = [
      {
        'address' => 'test.com',
        'id' => 101,
        'hostgroups' => [
                          zero
                          'one',
                          'or many'
                        ],
        'host_name' => 'test.com',
        'alias' => 'test.com',
        'template' => 'generic',
        'file_id' => 'etc/config'
      },
      {
        'address' => 'test2.com',
        'id' => 102,
        'hostgroups' => [
                          zero
                          'one',
                          'or many'
                        ],
        'host_name' => 'test2.com',
        'alias' => 'test2.com',
        'template' => 'generic',
        'file_id' => 'etc/config'
      },
      (..)
raimondsL
  • 333
  • 1
  • 12
  • 3
    Go has arrays, though you usually use slices. Go's hashes are called maps. There is no reason you can't create an array of maps or a map of arrays. Take the Go tour to get a handle on the basics: https://tour.golang.org – Adrian Jan 29 '19 at 14:17
  • 1
    Seems like similar question is [already answered](https://stackoverflow.com/questions/43379772/making-array-of-hashes-in-golang) – jiri.hofman Jan 29 '19 at 14:32
  • 1
    You can put a hash map into an array, just remember that Perl is one of the few languages (if not the only one) that supports auto-vivification. So, if you expect to have a dynamic hash that changes its structure and replicate that in golang, that's not going to work. – ChatterOne Jan 29 '19 at 14:33
  • Thanks everyone! type host map[string]interface{} and var hosts []host it is. I always search for all possible posts, but yesterday was kind of slow for me. – raimondsL Jan 30 '19 at 07:12

2 Answers2

1
var array = []map[string]interface{}{
    {"address": "test.com", "hostgroups": []string{"zero", "one", "or many"}, "id": 101},
    {"address": "test2.com", "hostgroups": []string{"zero", "one", "or many"}, "id": 102},
}
jiri.hofman
  • 127
  • 1
  • 3
  • 10
0

This is the answer.

type host map[string]interface{}

var hosts []host

h := host{
    "id":         id,
    "file_id":    "etc/config/hosts.cfg",
    "host_name":  host_name,
    "alias":      host_name,
    "address":    host_name,
    "hostgroups": hg,
    "template":   "generic-host",
}

hosts = append(hosts, h)
raimondsL
  • 333
  • 1
  • 12