github.com/MontFerret/ferret@v0.18.0/pkg/stdlib/strings/json.go (about)

     1  package strings
     2  
     3  import (
     4  	"context"
     5  	"encoding/json"
     6  
     7  	"github.com/wI2L/jettison"
     8  
     9  	"github.com/MontFerret/ferret/pkg/runtime/core"
    10  	"github.com/MontFerret/ferret/pkg/runtime/values"
    11  )
    12  
    13  // JSON_PARSE returns a value described by the JSON-encoded input string.
    14  // @param {String} str - The string to parse as JSON.
    15  // @return {Any} - Parsed value.
    16  func JSONParse(_ context.Context, args ...core.Value) (core.Value, error) {
    17  	err := core.ValidateArgs(args, 1, 1)
    18  
    19  	if err != nil {
    20  		return values.EmptyString, err
    21  	}
    22  
    23  	var val interface{}
    24  
    25  	err = json.Unmarshal([]byte(args[0].String()), &val)
    26  
    27  	if err != nil {
    28  		return values.EmptyString, err
    29  	}
    30  
    31  	return values.Parse(val), nil
    32  }
    33  
    34  // JSON_STRINGIFY returns a JSON string representation of the input value.
    35  // @param {Any} str - The input value to serialize.
    36  // @return {String} - JSON string.
    37  func JSONStringify(_ context.Context, args ...core.Value) (core.Value, error) {
    38  	err := core.ValidateArgs(args, 1, 1)
    39  
    40  	if err != nil {
    41  		return values.EmptyString, err
    42  	}
    43  
    44  	out, err := jettison.MarshalOpts(args[0])
    45  
    46  	if err != nil {
    47  		return values.EmptyString, err
    48  	}
    49  
    50  	return values.NewString(string(out)), nil
    51  }