Use Go lang with Gin to return an empty array instead of null for JSON responses

I have a struct:

type ProductConstructed struct {
    Name string `json:"Name"`
    BrandMedals []string `json:"BRAND_MEDALS"`
}

When I use gin to return my object:

func  constructProduct(c *gin.Context) {
    var response ProductConstructed 
    response.Name = "toto"

    c.JSON(200, response)
}

func main() {
    var err error
    if err != nil {
        panic(err)
    }
    //gin.SetMode(gin.ReleaseMode)
    r := gin.Default()
    r.POST("/constructProductGo/v1/constructProduct", constructProduct)
    r.Run(":8200") // listen and serve on 0.0.0.0:8080
}

The output is:

null

But it should be:

[]

How can I make it return an empty array?

Answer №1

After much deliberation, the decision was made to start by setting it up this way:

productCreated.BrandMedals = make([]string, 0)

Answer №2

To provide a clear explanation of why the solution above is effective:

slice1 has been declared but not defined, meaning no value has been assigned to it yet, resulting in it being equal to nil. When serialized, this will return as null.

slice2, on the other hand, has been both declared and defined. It is set to an empty slice rather than nil. After serialization, it will display as [].

var slice1 []string  // nil slice
slice2 := []string{} // zero-length but non-nil

json1, _ := json.Marshal(slice1)
json2, _ := json.Marshal(slice2)

fmt.Printf("%s\n", json1) // null
fmt.Printf("%s\n", json2) // []

fmt.Println(slice1 == nil) // true
fmt.Println(slice2 == nil) // false

Test it out on Go playground: https://play.golang.org/p/abc123xyz

For more information, visit: https://github.com/golang/go/wiki/CodeReviewComments#declaring-empty-slices

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

How can I update my outdated manifest v2 code to manifest v3 for my Google Chrome Extension?

Currently, I am developing an extension and using a template from a previous YouTube video that is based on manifest v2. However, I am implementing manifest v3 in my extension. Can anyone guide me on how to update this specific piece of code? "backgro ...

CSS background image referencing in React to the public folder's path

I am currently working on a project using Create-React-App and I am trying to set a background image for my header section. Here is how I'm attempting to do it: background-image: url('~/Screenshot_11.png'); However, I encountered an error w ...

What is the process of using an if statement in jQuery to verify the existence of a property in a JSON file?

I am working on a task to incorporate an if statement that checks for the existence of a specific property in a JSON file. If the property exists, I need to display its value within HTML tags <div class='titleHolder'> and "<div class=&ap ...

What is the best way to add custom styles to an Ext JS 'tabpanel' xtype using the 'style

Is there a way to change the style of a Ext.tab.Panel element using inline CSS structure like how it's done for a xtype: button element? { xtype: "button", itemId: "imageUploadButton1", text: "Uploader", style: { background : ' ...

Is it acceptable to replicate another individual's WordPress theme and website design in order to create my own WordPress website that looks identical to theirs?

It may sound shady, but a friend of mine boasts about the security of his WordPress website, claiming it's impossible to copy someone else's layout or theme. However, my limited experience in web development tells me otherwise. I believe it is po ...

Utilizing Javascript to Extract Data from Twitter Json Files

Can someone provide assistance with parsing JSON feed text retrieved from Twitter? I am looking to access and apply style tags to elements like the link, created date, and other information. Any tips on how I can achieve this task successfully would be g ...

Why is the toggle list not functioning properly following the JSON data load?

I attempted to create a color system management, but as a beginner, I find it quite challenging! My issue is: When I load my HTML page, everything works fine. However, when I click on the "li" element to load JSON, all my toggle elements stop working!!! ...

Retrieve jQuery CSS styles from a JSON database

I've been attempting to pass CSS attributes into a jQuery method using data stored in a JSON database. However, it doesn't seem to be functioning as expected. I suspect that directly inputting the path to the JSON variable may not be the correct ...

Is there a way to open an HTML file within the current Chrome app window?

Welcome, My goal is to create a Chrome App that serves as a replacement for the Chrome Dev Editor. Here is my current progress: background.js chrome.app.runtime.onLaunched.addListener(function() { chrome.app.window.create('backstage.html', { ...

Modifying the color of a variety of distinct data points

There was a previous inquiry regarding Changing Colour of Specific Data, which can be found here: Changing colour of specific data Building upon that question, I now have a new query. After successfully changing the 2017 dates to pink, I am seeking a way ...

fullcalendar adjusting color while being moved

Currently, I have implemented a fullcalendar feature that displays entries for multiple users with different colored calendars. However, there seems to be an issue when dragging an entry to another date - the color reverts back to default. Below is an exa ...

Trouble displaying data in Jquery JSON

I've been on the hunt for hours, trying to pinpoint where the issue lies within my code. Despite scouring different resources and sites, I can't seem to figure it out. Whenever I click "Get JSON Data," nothing seems to display below. Can someone ...

Writing CSS rules for generating HTML code when sending emails through the command line in Go

When trying to compose HTML with CSS for email delivery using Go command line execution, errors related to CSS properties are popping up. For instance, it's showing "not found" error in the terminal for properties like background: rgb(255, 255, 255) o ...