Closed fabiobulgarella closed 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):
cbor
struct field's tag if presentjson
struct field's tag if presentHere, 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.
Hi @fxamacker, thanks for your answer.
Yes, this solution works for my needs. Thank you again for the support!
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:
I would like to encode and decode this struct without considering the JSON tags, effectively treating it as:
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