Ver código fonte

fix JSON.parse with reviver

Mihail Stoykov 5 anos atrás
pai
commit
9025f726e6
2 arquivos alterados com 16 adições e 2 exclusões
  1. 2 2
      builtin_json.go
  2. 14 0
      builtin_json_test.go

+ 2 - 2
builtin_json.go

@@ -153,7 +153,7 @@ func (r *Runtime) builtinJSON_reviveWalk(reviver func(FunctionCall) Value, holde
 		value = _undefined
 	}
 
-	if object := value.(*Object); object != nil {
+	if object, ok := value.(*Object); ok {
 		if isArray(object) {
 			length := object.self.getStr("length").ToInteger()
 			for index := int64(0); index < length; index++ {
@@ -167,7 +167,7 @@ func (r *Runtime) builtinJSON_reviveWalk(reviver func(FunctionCall) Value, holde
 			}
 		} else {
 			for item, f := object.self.enumerate(false, false)(); f != nil; item, f = f() {
-				value := r.builtinJSON_reviveWalk(reviver, object, name)
+				value := r.builtinJSON_reviveWalk(reviver, object, newStringValue(item.name))
 				if value == _undefined {
 					object.self.deleteStr(item.name, false)
 				} else {

+ 14 - 0
builtin_json_test.go

@@ -47,6 +47,20 @@ func TestJSONMarshalObjectCircular(t *testing.T) {
 	}
 }
 
+func TestJSONParseReviver(t *testing.T) {
+	// example from
+	// https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/JSON/parse
+	const SCRIPT = `
+	JSON.parse('{"p": 5}', function(key, value) {
+	  return typeof value === 'number'
+        ? value * 2 // return value * 2 for numbers
+	    : value     // return everything else unchanged
+	 })["p"]
+	`
+
+	testScript1(SCRIPT, intToValue(10), t)
+}
+
 func BenchmarkJSONStringify(b *testing.B) {
 	b.StopTimer()
 	vm := New()