Json encode byte array as hex string instead of base64

I’m trying to marshal an interface{} object to json format and print it to a nicer view, it’s almost OK except for byte array.
I knew that by default

Array and slice values encode as JSON arrays, except that []byte encodes as a base64-encoded string, and a nil slice encodes as the null JSON value.

But I’d like to print these byte array in hex string instead of base64 (because it’s more farmilliar for a blockchain address/tx).
I cannot pre-define struct for that and a custom MarshalJson function because this object actually was not initiated by me but decoded from another data format (cbor) then it’s structure may vary.
Does anyone have workaround for this?
The data when I print in hex by fmt.Printf("%x\n", data)

map[0:[[9c37cb5294abce709bfa57bdcab039d75e212a503bc48d5b45e6ff4eb6272759 1] [77df5bd720b6fb8699762fea21bdbc8193a61b770a59443266383ba01a6b8900 1]] 1:[[00177a56a4202e7edd0f394bb850b9dfe072e205f947d7ccb3f8dcb476e10a200512c808028cbbf6758978026a2d8ed307c65de78625d7596c 64] [0067fa035e20501b0507356e7e75278f9f30dad9a8fe3826798b3ee0b0e10a200512c808028cbbf6758978026a2d8ed307c65de78625d7596c a]] 2:64]

Hi @Yenle9,

You can write a custom marshaller, using encoding/hex to handle the byte-slice-to-hex conversion. I found an example on StackOverflow: How to force go to encode `[8]byte` as hex when marshaling to json - Stack Overflow

Maybe I’m missing something, but that’s not exactly simple for OP because of

One must use reflection to walk and copy the original object replacing byte arrays with the user-defined type for which the MarshalJSON method is defined, but there’s probably no better way. An even uglier alternative is to post-process the JSON.

1 Like

Good point, I clearly overlooked the “may vary” part.

This topic was automatically closed 90 days after the last reply. New replies are no longer allowed.