8

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.

2 Answers 2

11

Quite straightforward as @swoogan comments:

package main

import (
    "encoding/json"
    "fmt"
)

type myJSON struct {
    Array []string
}

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

Demo avaliable here.

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

Comments

2

You need to import "encoding/json" and then use json.Marshal with your structure.

https://golang.org/pkg/encoding/json/#example_Marshal

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.