Json data not displaying

Hi,
When I GET the data from the following function, I can get it printed out using fmt.Println but it in the browser and in the postman I get following.
[
{},
{},
{}
]
The function is the following.

func sendResponse(w http.ResponseWriter, statusCode int, payload interface{}){

fmt.Println("Payload Unmarshal ",payload)
// prints this >> Payload Unmarshal [{1 Java} {2 python} {3 golang}]

response, _ := json.Marshal(payload)

w.Header().Set(“Content-Type”,“application/json; charset=utf-8”)

w.WriteHeader(statusCode)

fmt.Println("From sendResponse app ",response)
// Prints this >> From sendResponse app [91 123 125 44 123 125 44 123 125 93]

w.Write(response)

}
Can anyone help me in this regard, what wrong is done in the code ?

First thing I see: you could be swallowing an error. Change this:

// From this...
response, _ := json.Marshal(payload)
// ... to this:
response, err := json.Marshal(payload)
if err != nil {
	fmt.Println("error:", err)
}

If you want to see what the json.Marshal’d string actually looks like you could also change this line:

// From this...
fmt.Println("From sendResponse app ",response)
// ... to this:
fmt.Println("From sendResponse app ", string(response))

Try that and let us know what you find.

Thanks for the reply, but It didn’t help :woozy_face:

fmt.Println("From sendResponse app ",response)
// Payload Unmarshal  [{1 Java} {2 python} {3 golang}]
fmt.Println("From sendResponse app ", string(response))
//  From sendResponse app  [{},{},{}]

Invalid JSON!??

Error: Parse error on line 1: [{1 Java} {2 python} { --^ Expecting ‘STRING’, ‘}’, got ‘NUMBER’

Nopes, this (Invalid JSON) is not the case !

What’s the type on payload? I suspect your problem is coming from code that isn’t visible here. Consider the following:

package main

import (
	"encoding/json"
	"fmt"
)

type Payload struct {
	ID    int
	Value string
}

func main() {
	payload := []Payload{{1, "Java"}, {2, "python"}, {3, "golang"}}
	fmt.Println(payload)
	response, err := json.Marshal(payload)
	if err != nil {
		fmt.Println("error:", err)
	}
	fmt.Println(string(response))
}

… which produces:

[{1 Java} {2 python} {3 golang}]
[{"ID":1,"Value":"Java"},{"ID":2,"Value":"python"},{"ID":3,"Value":"golang"}]

You can run it yourself in the playground. If you can tweak this to provide a reproducible example somebody here might be able to help you.

Thanks for replying and for your consideration. The code I am working on is here.
All what you should do in order to run the application is to run the docker-compose up and access the localhost:8080/languages to get all the languages.

Didn’t need to run it. Already found the problem:

type language struct {
	id int `json:"id"`
	name string `json:"name"`
}

Those fields aren’t exported. Change this to:

type language struct {
	ID int `json:"id"`
	Name string `json:"name"`
}
2 Likes

Bundle of thanks, it works now !
I didn’t pay attention to that :frowning:

Thanks once again :slight_smile: