httpexpect icon indicating copy to clipboard operation
httpexpect copied to clipboard

Handle FloatFormat and DigitSeparator when formatting slices/maps

Open gavv opened this issue 2 years ago • 2 comments

In DefaultFormatter.formatValue, when value is a number, we format it accordingly to FloatFormat and DigitSeparator settings (see formatFloatValue and reformatNumber funcs).

However, if value is slice or map, and it has numbers inside, settings are ignored for those numbers. We need to fix it.

Slices and maps are formatted using one of the two ways:

  • json.MarshalIndent
  • litter.Sdump

We need to ensure that MarshalIndent handles FloatFormat, and Sdump handles both FloatFormat and DigitSeparator. (MarshalIndent can't handle DigitSeparator because it would be invalid JSON).

To achieve this, we need to do the following:

  • for MarshalIndent:
    • recursively inspect value using reflect
    • find all numbers (integers, floats, big.Float, json.Number)
    • replace each number with a wrapper type that holds the number (e.g. in big.Float) and implements json.Marshaler interface; its MarshalJSON method should format number according to FloatFormat setting
  • for Sdump:
    • do the same, but instead of json.Marshaler, implement litter.Dumper interface; its LitterDump method should format number according to FloatFormat and DigitSeparator settings

We also need to adjust "colorjson" func in formatter.go. By default, it will reformat numbers using strconv.FormatFloat. We can try to prevent it by using json.Decoder instead of json.Unmarshal to parse json, and using Decoder.UseNumber() method. It will tell decoder to store numbers as json.Number, which colorjson should format as-is.

gavv avatar Oct 07 '23 13:10 gavv

Hi @gavv , can I give it a try?

nhAnik avatar Oct 10 '23 13:10 nhAnik

Sure, thanks!

gavv avatar Oct 10 '23 13:10 gavv