Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Go: Convert Strings Array to Json Array String

Tags:

json

go

Trying to convert a strings array to a json string in Go. But all I get is an array of numbers.

What am I missing?

package main

import (
    "fmt"
    "encoding/json"
)

func main() {
    var urls = []string{
        "http://google.com",
        "http://facebook.com",
        "http://youtube.com",
        "http://yahoo.com",
        "http://twitter.com",
        "http://live.com",
    }

    urlsJson, _ := json.Marshal(urls)
    fmt.Println(urlsJson)
}

Code on Go Playground: http://play.golang.org/p/z-OUhvK7Kk

like image 991
Joe Bergevin Avatar asked Jul 11 '14 03:07

Joe Bergevin


2 Answers

By marshaling the object, you are getting the encoding (bytes) that represents the JSON string. If you want the string, you have to convert those bytes to a string.

fmt.Println(string(urlsJson))
like image 54
Jeff Mercado Avatar answered Sep 22 '22 12:09

Jeff Mercado


Another way is to use directly os.Stdout.Write(urlsJson)

like image 45
fabrizioM Avatar answered Sep 23 '22 12:09

fabrizioM