github.com/hashicorp/hcl/v2@v2.20.0/json/is.go (about)

     1  // Copyright (c) HashiCorp, Inc.
     2  // SPDX-License-Identifier: MPL-2.0
     3  
     4  package json
     5  
     6  import (
     7  	"github.com/hashicorp/hcl/v2"
     8  )
     9  
    10  // IsJSONExpression returns true if and only if the given expression is one
    11  // that originated in a JSON document.
    12  //
    13  // Applications aiming to be syntax-agnostic should not use this function and
    14  // should instead use the normal expression evaluation or static analysis
    15  // APIs.
    16  //
    17  // However, JSON expressions do have a unique behavior whereby they interpret
    18  // the source JSON differently depending on the hcl.EvalContext value passed
    19  // to the Value method -- in particular, a nil hcl.EvalContext returns
    20  // literal strings rather than interpreting them as HCL template syntax --
    21  // and so in exceptional cases an application may wish to rely on that behavior
    22  // in situations where it specifically knows the expression originated in JSON,
    23  // in case it needs to do some non-standard handling of the expression in that
    24  // case.
    25  //
    26  // Caution: The normal HCL API allows for HCL expression implementations that
    27  // wrap other HCL expression implementations. This function will return false
    28  // if given an expression of some other type that encapsulates a JSON
    29  // expression, even if the wrapper implementation would in principle preserve
    30  // the special evaluation behavior of the wrapped expression.
    31  func IsJSONExpression(maybeJSONExpr hcl.Expression) bool {
    32  	_, ok := maybeJSONExpr.(*expression)
    33  	return ok
    34  }
    35  
    36  // IsJSONBody returns true if and only if the given body is one that originated
    37  // in a JSON document.
    38  //
    39  // Applications aiming to be syntax-agnostic should not use this function and
    40  // should instead use the normal schema-driven or "just attributes' decoding
    41  // APIs.
    42  //
    43  // Howeer, JSON expressions do have a unique behavior whereby various different
    44  // source JSON shapes can be interpreted in different ways depending on the
    45  // given schema, and so in exceptional cases an application may need to
    46  // perform some deeper analysis first in order to distinguish variants of
    47  // different physical structure.
    48  //
    49  // Caution: The normal HCL API allows for HCL body implementations that wrap
    50  // other HCL body implementations. This function will return false if given an
    51  // expression of some other type that encapsulates a JSON body, even if
    52  // the wrapper implementation would in principle preserve the special
    53  // decoding behavior of the wrapped body.
    54  func IsJSONBody(maybeJSONBody hcl.Body) bool {
    55  	_, ok := maybeJSONBody.(*body)
    56  	return ok
    57  }