6

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

3 Answers 3

16

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))
Sign up to request clarification or add additional context in comments.

Comments

1

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

Comments

0

You could use stdout output encoder:

package main

import (
   "encoding/json"
   "os"
)

func main() {
   json.NewEncoder(os.Stdout).Encode(urls)
}

or a string builder:

package main

import (
   "encoding/json"
   "strings"
)

func main() {
   b := new(strings.Builder)
   json.NewEncoder(b).Encode(urls)
   print(b.String())
}

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

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.