fxamacker / cbor

CBOR codec (RFC 8949) with CBOR tags, Go struct tags (toarray, keyasint, omitempty), float64/32/16, big.Int, and fuzz tested billions of execs.
MIT License
748 stars 61 forks source link

feature: Option to Ignore JSON Tags While Encoding and Decoding #536

Closed fabiobulgarella closed 6 months ago

fabiobulgarella commented 6 months ago

Hello,

First, thank you for maintaining the fxamacker/cbor library.

I have a question regarding the encoding and decoding processes. Is there a way to configure the library to ignore JSON tags in struct fields during CBOR encoding and decoding? For example, consider the following Go struct:

type Example struct {
    Field1 string `json:"field1"`
    Field2 int    `json:"field2"`
    Field3 bool   `json:"-"`
}

I would like to encode and decode this struct without considering the JSON tags, effectively treating it as:

type Example struct {
    Field1 string
    Field2 int
    Field3 bool // this field would be encoded and not ignored
}

This feature would be very helpful in scenarios where JSON tags are present for other serialization needs, but we want CBOR encoding/decoding to disregard them.

Is this currently possible with the library? If not, is there any plan to support this feature, or could it be considered for future releases?

Thank you for your time and assistance.

Best Regards

fxamacker commented 6 months ago

Hi Fabio,

Is there a way to configure the library to ignore JSON tags in struct fields during CBOR encoding and decoding?

Currently, we can ignore JSON field tags by specifying any CBOR field tag (e.g. cbor:",") on the same field.

cbor.Marshal() encodes struct fields using (in this order):

Here, Example struct has both json and cbor tags:

https://go.dev/play/p/QUTE0SFSLhn

package main

import (
    "encoding/json"
    "fmt"

    "github.com/fxamacker/cbor/v2"
)

type Example struct {
    Field1 string `json:"field1" cbor:","`
    Field2 int    `json:"field2" cbor:","`
    Field3 bool   `json:"-" cbor:","`
}

func main() {
    var example Example

    b, _ := json.Marshal(example)
    fmt.Printf("json: %s\n", string(b))

    b, _ = cbor.Marshal(example)
    fmt.Printf("cbor: %x\n", b)
    diagnose, _ := cbor.Diagnose(b)
    fmt.Printf("cbor edn: %s\n", diagnose)

    // Output:
    // json: {"field1":"","field2":0}
    // cbor: a3664669656c643160664669656c643200664669656c6433f4
    // cbor edn: {"Field1": "", "Field2": 0, "Field3": false}
}

Please let me know if this works for you.

fabiobulgarella commented 6 months ago

Hi @fxamacker, thanks for your answer.

Yes, this solution works for my needs. Thank you again for the support!