MCPcopy Create free account
hub / github.com/cel-expr/cel-go / jsonEncodeValue

Function jsonEncodeValue

ext/encoders.go:446–513  ·  view source on GitHub ↗
(val ref.Val)

Source from the content-addressed store, hash-verified

444}
445
446func jsonEncodeValue(val ref.Val) (string, error) {
447 switch v := val.(type) {
448 case types.Bool:
449 if v {
450 return "true", nil
451 }
452 return "false", nil
453 case types.Null:
454 return "null", nil
455 case types.Int:
456 if v >= -9007199254740991 && v <= 9007199254740991 {
457 return strconv.FormatInt(int64(v), 10), nil
458 }
459 return strconv.Quote(strconv.FormatInt(int64(v), 10)), nil
460 case types.Uint:
461 if v <= 9007199254740991 {
462 return strconv.FormatUint(uint64(v), 10), nil
463 }
464 return strconv.Quote(strconv.FormatUint(uint64(v), 10)), nil
465 case types.Double:
466 f := float64(v)
467 if math.IsNaN(f) || math.IsInf(f, 0) {
468 return "", fmt.Errorf("json encode error: NaN and Inf are not supported in JSON")
469 }
470 b, _ := json.Marshal(f)
471 return string(b), nil
472 case types.String:
473 str := string(v)
474 if len(str) < 128 && !strings.ContainsAny(str, "\"\\\n\r\t\x00\x01\x02\x03\x04\x05\x06\x07\x08\x0b\x0c\x0e\x0f\x10\x11\x12\x13\x14\x15\x16\x17\x18\x19\x1a\x1b\x1c\x1d\x1e\x1f<>&") {
475 return strconv.Quote(str), nil
476 }
477 b, _ := json.Marshal(str)
478 return string(b), nil
479 case types.Bytes:
480 return strconv.Quote(base64.StdEncoding.EncodeToString([]byte(v))), nil
481 }
482 if msg, ok := getProtoMessage(val); ok {
483 jsonBytes, err := protojson.Marshal(msg)
484 if err != nil {
485 return "", err
486 }
487 return string(jsonBytes), nil
488 }
489 if val.Type().HasTrait(traits.FieldTesterType) {
490 if encoded, ok := jsonEncodeNativeStruct(val.Value()); ok {
491 return encoded, nil
492 }
493 }
494 if lister, ok := val.(traits.Lister); ok {
495 return jsonEncodeList(lister)
496 }
497 if mapper, ok := val.(traits.Mapper); ok {
498 return jsonEncodeMap(mapper)
499 }
500 native, err := val.ConvertToNative(types.JSONValueType)
501 if err != nil {
502 return "", err
503 }

Callers 6

CompileOptionsMethod · 0.85
JSONEncodeFunction · 0.85
jsonEncodeListFunction · 0.85
jsonEncodeMapFunction · 0.85
yamlEncodeValueFunction · 0.85

Calls 8

getProtoMessageFunction · 0.85
jsonEncodeNativeStructFunction · 0.85
jsonEncodeListFunction · 0.85
jsonEncodeMapFunction · 0.85
HasTraitMethod · 0.65
TypeMethod · 0.65
ValueMethod · 0.65
ConvertToNativeMethod · 0.65

Tested by 1