github.com/GuanceCloud/cliutils@v1.1.21/pipeline/ptinput/funcs/fn_valid_json.go (about)

     1  // Unless explicitly stated otherwise all files in this repository are licensed
     2  // under the MIT License.
     3  // This product includes software developed at Guance Cloud (https://www.guance.com/).
     4  // Copyright 2021-present Guance, Inc.
     5  
     6  package funcs
     7  
     8  import (
     9  	"encoding/json"
    10  	"fmt"
    11  
    12  	"github.com/GuanceCloud/platypus/pkg/ast"
    13  	"github.com/GuanceCloud/platypus/pkg/engine/runtime"
    14  	"github.com/GuanceCloud/platypus/pkg/errchain"
    15  )
    16  
    17  func ValidJSONChecking(ctx *runtime.Task, funcExpr *ast.CallExpr) *errchain.PlError {
    18  	if len(funcExpr.Param) != 1 {
    19  		return runtime.NewRunError(ctx, fmt.Sprintf(
    20  			"func %s expects 1 arg", funcExpr.Name), funcExpr.NamePos)
    21  	}
    22  	return nil
    23  }
    24  
    25  func ValidJSON(ctx *runtime.Task, funcExpr *ast.CallExpr) *errchain.PlError {
    26  	val, _, err := runtime.RunStmt(ctx, funcExpr.Param[0])
    27  	if err != nil {
    28  		return err
    29  	}
    30  
    31  	if val != nil {
    32  		if v, ok := val.(string); ok {
    33  			valid := json.Valid([]byte(v))
    34  			ctx.Regs.ReturnAppend(valid, ast.Bool)
    35  			return nil
    36  		}
    37  	}
    38  
    39  	ctx.Regs.ReturnAppend(false, ast.Bool)
    40  	return nil
    41  }