Chris Chris - 2 years ago 106
JSON Question

Creating JSON array in Go

How do I construct and send a JSON array with Go?

For example:

{ myArray: ["one", "two", "three"] }

At the moment the closest I can get it sending JSON down to the browser as a string like this:

{ myArrayString: '["once", "two", "three"]' }

Which is not what I'm trying to achieve.

Answer Source

Quite straightforward as @swoogan comments:

package main

import (

type myJSON struct {
    Array []string

func main() {
    jsondat := &myJSON{Array: []string{"one", "two", "three"}}
    encjson, _ := json.Marshal(jsondat)

Demo avaliable here.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download