Browse Source

codec: json: decode json null as a string

Previously, we only treated "..." as a string. Now we also look for
and handle null as a string, and return an empty string or a nil byte,
depending on the context.

Fixes #182 #180
Ugorji Nwoke 9 years ago
parent
commit
9c7f9b7a2b
1 changed files with 13 additions and 0 deletions
  1. 13 0
      codec/json.go

+ 13 - 0
codec/json.go

@@ -931,6 +931,11 @@ func (d *jsonDecDriver) DecodeBytes(bs []byte, isstring, zerocopy bool) (bsOut [
 	if isstring {
 		return d.bs
 	}
+	// if appendStringAsBytes returned a zero-len slice, then treat as nil.
+	// This should only happen for null, and "".
+	if len(d.bs) == 0 {
+		return nil
+	}
 	bs0 := d.bs
 	slen := base64.StdEncoding.DecodedLen(len(bs0))
 	if slen <= cap(bs) {
@@ -968,6 +973,14 @@ func (d *jsonDecDriver) appendStringAsBytes() {
 		}
 		d.tok = b
 	}
+
+	// handle null as a string
+	if d.tok == 'n' {
+		d.readStrIdx(10, 13) // ull
+		d.bs = d.bs[:0]
+		return
+	}
+
 	if d.tok != '"' {
 		d.d.errorf("json: expect char '%c' but got char '%c'", '"', d.tok)
 	}