Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Creating JSON array in Go

Tags:

json

arrays

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.

like image 505
Chris Avatar asked Jun 16 '26 13:06

Chris


1 Answers

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.

like image 167
Juan Diego Godoy Robles Avatar answered Jun 19 '26 01:06

Juan Diego Godoy Robles



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!