Make 'default' param of json.decode keyword or positional
Following the discussion at https://github.com/google/starlark-go/pull/466
RELNOTES: the 'default' param of json.decode can now be used as a keyword
parameter.
PiperOrigin-RevId: 535643654
Change-Id: Ie203548ba46e037db6ce2303bfcd156edf7e96c9
diff --git a/src/main/java/net/starlark/java/lib/json/Json.java b/src/main/java/net/starlark/java/lib/json/Json.java
index c13da7e..608a046 100644
--- a/src/main/java/net/starlark/java/lib/json/Json.java
+++ b/src/main/java/net/starlark/java/lib/json/Json.java
@@ -290,17 +290,16 @@
+ " string occurs more than once in the object, the last value for the key is kept.\n"
+ "<li>a JSON array is parsed as new unfrozen Starlark list.\n"
+ "</ul>\n"
- + "If <code>x</code> is not a valid JSON encoding and the optional, positional-only"
+ + "If <code>x</code> is not a valid JSON encoding and the optional"
+ " <code>default</code> parameter is specified (including specified as"
+ " <code>None</code>), this function returns the <code>default</code> value.\n"
+ "If <code>x</code> is not a valid JSON encoding and the optional"
- + " <code>default</code> parameter is <em>not</em> specified, this"
- + " function fails.",
+ + " <code>default</code> parameter is <em>not</em> specified, this function fails.",
parameters = {
@Param(name = "x", doc = "JSON string to decode."),
@Param(
- // positional-only to match Starlark language spec for dict.get(), dict.pop(), getattr()
name = "default",
+ named = true,
doc = "If specified, the value to return when <code>x</code> cannot be decoded.",
defaultValue = "unbound")
},
diff --git a/src/test/java/net/starlark/java/eval/testdata/json.star b/src/test/java/net/starlark/java/eval/testdata/json.star
index bf81227..0ce226c 100644
--- a/src/test/java/net/starlark/java/eval/testdata/json.star
+++ b/src/test/java/net/starlark/java/eval/testdata/json.star
@@ -151,15 +151,13 @@
## json.decode with default specified
+assert_eq(json.decode('{"valid": "json"}', default = "default value"), {"valid": "json"})
assert_eq(json.decode('{"valid": "json"}', "default value"), {"valid": "json"})
+assert_eq(json.decode('{"invalid": "json"', default = "default value"), "default value")
assert_eq(json.decode('{"invalid": "json"', "default value"), "default value")
+assert_eq(json.decode('{"invalid": "json"', default = None), None)
assert_eq(json.decode('{"invalid": "json"', None), None)
-assert_fails(
- lambda: json.decode('{"invalid": "json"', default = "default value"),
- "got named argument for positional-only parameter 'default'",
-)
-
def codec(x):
return json.decode(json.encode(x))