You've already forked json-iterator
							
							
				mirror of
				https://github.com/json-iterator/go.git
				synced 2025-10-31 00:07:40 +02:00 
			
		
		
		
	Fix encoding 0-length arrays
The array encoder assumed that arrays had at least one value, so it would serialize them with a zero-value for the array, such as `[0]`. This adds a test to reproduce the issue, and updates the encoder to write an empty array if the length is 0.
This commit is contained in:
		| @@ -27,6 +27,10 @@ type arrayEncoder struct { | ||||
| } | ||||
|  | ||||
| func (encoder *arrayEncoder) Encode(ptr unsafe.Pointer, stream *Stream) { | ||||
| 	if encoder.arrayType.Len() == 0 { | ||||
| 		stream.WriteEmptyArray() | ||||
| 		return | ||||
| 	} | ||||
| 	stream.WriteArrayStart() | ||||
| 	elemPtr := unsafe.Pointer(ptr) | ||||
| 	encoder.elemEncoder.Encode(elemPtr, stream) | ||||
|   | ||||
| @@ -15,6 +15,15 @@ func Test_encode_fixed_array(t *testing.T) { | ||||
| 	should.Equal("[0.1,1]", output) | ||||
| } | ||||
|  | ||||
| func Test_encode_fixed_array_empty(t *testing.T) { | ||||
| 	should := require.New(t) | ||||
| 	type FixedArray [0]float64 | ||||
| 	fixed := FixedArray{} | ||||
| 	output, err := MarshalToString(fixed) | ||||
| 	should.Nil(err) | ||||
| 	should.Equal("[]", output) | ||||
| } | ||||
|  | ||||
| func Test_encode_fixed_array_of_map(t *testing.T) { | ||||
| 	should := require.New(t) | ||||
| 	type FixedArray [2]map[string]string | ||||
|   | ||||
		Reference in New Issue
	
	Block a user