@@ -111,6 +111,11 @@ function jsonToGo(json, typename, flatten = true, example = false, allOmitempty
111
111
continue
112
112
}
113
113
114
+ // if variable was first detected as int (7) and a second time as float64 (3.14)
115
+ // then we want to select float64, not int. Similar for int64 and float64.
116
+ if ( areSameType ( currentValue , 1 ) )
117
+ allFields [ keyname ] . value = findBestValueForNumberType ( existingValue , currentValue ) ;
118
+
114
119
if ( areObjects ( existingValue , currentValue ) ) {
115
120
const comparisonResult = compareObjectKeys (
116
121
Object . keys ( currentValue ) ,
@@ -389,6 +394,50 @@ function jsonToGo(json, typename, flatten = true, example = false, allOmitempty
389
394
}
390
395
}
391
396
397
+ // change the value to expand ints and floats to their larger equivalent
398
+ function findBestValueForNumberType ( existingValue , newValue ) {
399
+ if ( ! areSameType ( newValue , 1 ) ) {
400
+ console . error ( `Error: currentValue ${ newValue } is not a number` )
401
+ return null // falls back to goType "any"
402
+ }
403
+
404
+ const newGoType = goType ( newValue )
405
+ const existingGoType = goType ( existingValue )
406
+
407
+ if ( newGoType === existingGoType )
408
+ return existingValue
409
+
410
+ // always upgrade float64
411
+ if ( newGoType === "float64" )
412
+ return newValue
413
+ if ( existingGoType === "float64" )
414
+ return existingValue
415
+
416
+ // it's too complex to distinguish int types and float32, so we force-upgrade to float64
417
+ // if anyone has a better suggestion, PRs are welcome!
418
+ if ( newGoType . includes ( "float" ) && existingGoType . includes ( "int" ) )
419
+ return Number . MAX_VALUE
420
+ if ( newGoType . includes ( "int" ) && existingGoType . includes ( "float" ) )
421
+ return Number . MAX_VALUE
422
+
423
+ if ( newGoType . includes ( "int" ) && existingGoType . includes ( "int" ) ) {
424
+ const existingValueAbs = Math . abs ( existingValue ) ;
425
+ const newValueAbs = Math . abs ( newValue ) ;
426
+
427
+ // if the sum is overflowing, it's safe to assume numbers are very large. So we force int64.
428
+ if ( ! isFinite ( existingValueAbs + newValueAbs ) )
429
+ return Number . MAX_SAFE_INTEGER
430
+
431
+ // it's too complex to distinguish int8, int16, int32 and int64, so we just use the sum as best-guess
432
+ return existingValueAbs + newValueAbs ;
433
+ }
434
+
435
+ // There should be other cases
436
+ console . error ( `Error: something went wrong with findBestValueForNumberType() using the values: '${ newValue } ' and '${ existingValue } '` )
437
+ console . error ( " Please report the problem to https://github.com/mholt/json-to-go/issues" )
438
+ return null // falls back to goType "any"
439
+ }
440
+
392
441
// Given two types, returns the more specific of the two
393
442
function mostSpecificPossibleGoType ( typ1 , typ2 )
394
443
{
0 commit comments