Parses a JSON string as a Starlark value.
(String x, Object defaultValue, StarlarkThread thread)
| 316 | |
| 317 | /** Parses a JSON string as a Starlark value. */ |
| 318 | @StarlarkMethod( |
| 319 | name = "decode", |
| 320 | doc = |
| 321 | "The decode function has one required positional parameter: a JSON string.\n" |
| 322 | + "It returns the Starlark value that the string denotes.\n" |
| 323 | + "<ul><li><code>\"null\"</code>, <code>\"true\"</code> and <code>\"false\"</code>" |
| 324 | + " are parsed as <code>None</code>, <code>True</code>, and <code>False</code>.\n" |
| 325 | + "<li>Numbers are parsed as int, or as a float if they contain a decimal point or an" |
| 326 | + " exponent. Although JSON has no syntax for non-finite values, very large values" |
| 327 | + " may be decoded as infinity.\n" |
| 328 | + "<li>a JSON object is parsed as a new unfrozen Starlark dict. If the same key" |
| 329 | + " string occurs more than once in the object, the last value for the key is kept.\n" |
| 330 | + "<li>a JSON array is parsed as new unfrozen Starlark list.\n" |
| 331 | + "</ul>\n" |
| 332 | + "If <code>x</code> is not a valid JSON encoding and the optional" |
| 333 | + " <code>default</code> parameter is specified (including specified as" |
| 334 | + " <code>None</code>), this function returns the <code>default</code> value.\n" |
| 335 | + "If <code>x</code> is not a valid JSON encoding and the optional" |
| 336 | + " <code>default</code> parameter is <em>not</em> specified, this function fails.", |
| 337 | parameters = { |
| 338 | @Param(name = "x", doc = "JSON string to decode."), |
| 339 | @Param( |
| 340 | name = "default", |
| 341 | named = true, |
| 342 | doc = "If specified, the value to return when <code>x</code> cannot be decoded.", |
| 343 | defaultValue = "unbound") |
| 344 | }, |
| 345 | useStarlarkThread = true) |
| 346 | public Object decode(String x, Object defaultValue, StarlarkThread thread) throws EvalException { |
| 347 | try { |
| 348 | return new Decoder( |
| 349 | thread.mutability(), |
| 350 | x, |
| 351 | thread |
| 352 | .getSemantics() |
| 353 | .getBool(StarlarkSemantics.INTERNAL_BAZEL_ONLY_UTF_8_BYTE_STRINGS)) |
| 354 | .decode(); |
| 355 | } catch (EvalException e) { |
| 356 | if (defaultValue != Starlark.UNBOUND) { |
| 357 | return defaultValue; |
| 358 | } else { |
| 359 | throw e; |
| 360 | } |
| 361 | } |
| 362 | } |
| 363 | |
| 364 | private static final class Decoder { |
| 365 |