go.chromium.org/luci@v0.0.0-20240309015107-7cdc2e660f33/lucicfg/json.go (about)

     1  // Copyright 2020 The LUCI Authors.
     2  //
     3  // Licensed under the Apache License, Version 2.0 (the "License");
     4  // you may not use this file except in compliance with the License.
     5  // You may obtain a copy of the License at
     6  //
     7  //      http://www.apache.org/licenses/LICENSE-2.0
     8  //
     9  // Unless required by applicable law or agreed to in writing, software
    10  // distributed under the License is distributed on an "AS IS" BASIS,
    11  // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
    12  // See the License for the specific language governing permissions and
    13  // limitations under the License.
    14  
    15  package lucicfg
    16  
    17  import (
    18  	"encoding/json"
    19  	"fmt"
    20  
    21  	"go.starlark.net/starlark"
    22  
    23  	"go.chromium.org/luci/starlark/builtins"
    24  )
    25  
    26  // toSortedJSON is to_json(value) builtin.
    27  //
    28  // It historically preceded json.encode(...). Unlike json.encode(...) it emits
    29  // JSON with dict keys sorted.
    30  var toSortedJSON = starlark.NewBuiltin("to_json", func(_ *starlark.Thread, fn *starlark.Builtin, args starlark.Tuple, kwargs []starlark.Tuple) (starlark.Value, error) {
    31  	var v starlark.Value
    32  	if err := starlark.UnpackPositionalArgs(fn.Name(), args, kwargs, 1, &v); err != nil {
    33  		return nil, err
    34  	}
    35  	obj, err := builtins.ToGoNative(v)
    36  	if err != nil {
    37  		return nil, fmt.Errorf("to_json: %s", err)
    38  	}
    39  	blob, err := json.Marshal(obj)
    40  	if err != nil {
    41  		return nil, fmt.Errorf("to_json: %s", err)
    42  	}
    43  	return starlark.String(blob), nil
    44  })