openlang

I want my nulls preserved

Hello,

I want to preserve nulls arriving as JSON from a REST API server. At the moment I unmarshal into a struct, which changes those Nulls to zero values.

Could somebody share a small example or a helpful video link? I've attempted pointers without grasping their benefit, since the zero values still appear.

The conversation continues 3

Follow the reasoning
  1. Permalink

    Hi fernvale_54,

    As mossglen_55 already pointed out, you can represent a value with a pointer to indicate that the corresponding data might be absent

    type Entry struct {
        Text *string `json:"bar"`
    }

    When using a value which could possibly be null, remember to check for null before treating that value as one that actually exists, or you'll hit panic: runtime error: invalid memory address or nil pointer dereference, something along these lines works:

    var entry Entry
    
    //...unmarsal into Entry
    
    if entry.Text != nil {
        // len() is safe in this branch
        fmt.Println(len(*entry.Text))
    }

    For tidier JSON output, also investigate the omitempty and omitzero tags (omitzero arrived with go 1.24 and is fairly recent, so information about it might still be sparse)

  2. Permalink

    One pleasant feature of go is that len() is static. Before taking a slice's length, or even iterating through it, a null check isn't necessary. For most operations, a nil-slice acts as though its length were 0.

    For the remaining primitives, structs and maps, however, your point stands.

Other sides of the same question

  1. What is the MySQL SELECT syntax for a conditional expression?

    I'm working in MySQL and would like something resembling a ternary expression in SQL, for example: The output would look roug…

    Replies 2Latest activity sql
  2. Removing an optional column safely with PostgreSQL 9+

    I want to remove a column belonging to a table. What's the way to determine whether that column is present? I read the manual…

    Replies 2Latest activity sql
  3. Missing field through a derived table in SQL

    I'm executing the following SQL statement: It produces the following error: #1054 - Unknown column 'shipping.post_id' in 'on…

    Replies 2Latest activity sql