// MaterializeWithJSON converts log Fields into JSON string
// TODO refactor into pluggable materializer
553792
func MaterializeWithJSON(logFields []log.Field) ([]byte, error) {
	fields := fieldsAsMap(make(map[string]string, len(logFields)))
	for _, field := range logFields {
		field.Marshal(fields)
	}
	if event, ok := fields["event"]; ok && len(fields) == 1 {
		return []byte(event), nil
	}
	return json.Marshal(fields)
}
1008586
func GetLoggerWithFields(ctx context.Context, fields map[interface{}]interface{}, keys ...interface{}) Logger {
	// must convert from interface{} -> interface{} to string -> interface{} for logrus.
	lfields := make(logrus.Fields, len(fields))
	for key, value := range fields {
		lfields[fmt.Sprint(key)] = value
	}

	return getLogrusLogger(ctx, keys...).WithFields(lfields)
}
369931
func WrapWithCastAsJSON(ctx sessionctx.Context, expr Expression) Expression {
	if expr.GetType().Tp == mysql.TypeJSON && !mysql.HasParseToJSONFlag(expr.GetType().Flag) {
		return expr
	}
	tp := &types.FieldType{
		Tp:      mysql.TypeJSON,
		Flen:    12582912, // FIXME: Here the Flen is not trusted.
		Decimal: 0,
		Charset: mysql.DefaultCharset,
		Collate: mysql.DefaultCollationName,
		Flag:    mysql.BinaryFlag,
	}
	return BuildCastFunction(ctx, expr, tp)
}
1125249
func PublishJSON(ctx context.Context, topic string, obj interface{}) *PublishResult {
	pr := &PublishResult{Ready: make(chan struct{})}
	go func() {
		err := client.Publish(ctx, topic, obj, true)
		pr.Err = err
		close(pr.Ready)
	}()
	return pr
}
271538
func (c *Context) BindJSON(obj interface{}) error {
	return c.MustBindWith(obj, binding.JSON)
}
252771
func LoadJSON(raw json.RawMessage) (*Config, error) {
	obj, err := hcl.Parse(string(raw))
	if err != nil {
		return nil, fmt.Errorf(
			"Error parsing JSON document as HCL: %s", err)
	}

	// Start building the result
	hclConfig := &hclConfigurable{
		Root: obj,
	}

	return hclConfig.Config()
}
1287913
func (c *LayerTree) CompositingReasonsWithParams(v *LayerTreeCompositingReasonsParams) ([]string, error) {
	resp, err := gcdmessage.SendCustomReturn(c.target, c.target.GetSendCh(), &gcdmessage.ParamRequest{Id: c.target.GetId(), Method: "LayerTree.compositingReasons", Params: v})
	if err != nil {
		return nil, err
	}

	var chromeData struct {
		Result struct {
			CompositingReasons []string
		}
	}

	if resp == nil {
		return nil, &gcdmessage.ChromeEmptyResponseErr{}
	}

	// test if error first
	cerr := &gcdmessage.ChromeErrorResponse{}
	json.Unmarshal(resp.Data, cerr)
	if cerr != nil && cerr.Error != nil {
		return nil, &gcdmessage.ChromeRequestErr{Resp: cerr}
	}

	if err := json.Unmarshal(resp.Data, &chromeData); err != nil {
		return nil, err
	}

	return chromeData.Result.CompositingReasons, nil
}
291440
func WriteJSON(writer io.Writer, v interface{}, options JSON, enableOptimization ...bool) (int, error) {
	var (
		result   []byte
		err      error
		optimize = len(enableOptimization) > 0 && enableOptimization[0]
	)

	if indent := options.Indent; indent != "" {
		marshalIndent := json.MarshalIndent
		if optimize {
			marshalIndent = jsoniter.ConfigCompatibleWithStandardLibrary.MarshalIndent
		}

		result, err = marshalIndent(v, "", indent)
		result = append(result, newLineB...)
	} else {
		marshal := json.Marshal
		if optimize {
			marshal = jsoniter.ConfigCompatibleWithStandardLibrary.Marshal
		}

		result, err = marshal(v)
	}

	if err != nil {
		return 0, err
	}

	if options.UnescapeHTML {
		result = bytes.Replace(result, ltHex, lt, -1)
		result = bytes.Replace(result, gtHex, gt, -1)
		result = bytes.Replace(result, andHex, and, -1)
	}

	if prefix := options.Prefix; prefix != "" {
		result = append([]byte(prefix), result...)
	}

	return writer.Write(result)
}
877219
func (l Logger) With() Context {
	context := l.context
	l.context = make([]byte, 0, 500)
	if context != nil {
		l.context = append(l.context, context...)
	}
	return Context{l}
}
162163
func (l *intLogger) logJSON(t time.Time, level Level, msg string, args ...interface{}) {
	vals := l.jsonMapEntry(t, level, msg)
	args = append(l.implied, args...)

	if args != nil && len(args) > 0 {
		if len(args)%2 != 0 {
			cs, ok := args[len(args)-1].(CapturedStacktrace)
			if ok {
				args = args[:len(args)-1]
				vals["stacktrace"] = cs
			} else {
				args = append(args, "<unknown>")
			}
		}

		for i := 0; i < len(args); i = i + 2 {
			if _, ok := args[i].(string); !ok {
				// As this is the logging function not much we can do here
				// without injecting into logs...
				continue
			}
			val := args[i+1]
			switch sv := val.(type) {
			case error:
				// Check if val is of type error. If error type doesn't
				// implement json.Marshaler or encoding.TextMarshaler
				// then set val to err.Error() so that it gets marshaled
				switch sv.(type) {
				case json.Marshaler, encoding.TextMarshaler:
				default:
					val = sv.Error()
				}
			case Format:
				val = fmt.Sprintf(sv[0].(string), sv[1:]...)
			}

			vals[args[i].(string)] = val
		}
	}

	err := json.NewEncoder(l.writer).Encode(vals)
	if err != nil {
		if _, ok := err.(*json.UnsupportedTypeError); ok {
			plainVal := l.jsonMapEntry(t, level, msg)
			plainVal["@warn"] = errJsonUnsupportedTypeMsg

			json.NewEncoder(l.writer).Encode(plainVal)
		}
	}
}
306971
func ParseJSONWithOptions(data []byte, options *intrinsics.ProcessorOptions) (*cloudformation.Template, error) {

	// Process all AWS CloudFormation intrinsic functions (e.g. Fn::Join)
	intrinsified, err := intrinsics.ProcessJSON(data, options)
	if err != nil {
		return nil, err
	}

	return unmarshal(intrinsified)

}
151000
func (o *UploadArtifactOpts) MarshalJSON() ([]byte, error) {
	return json.Marshal(map[string]interface{}{
		"artifact_version": map[string]interface{}{
			"id":         o.ID,
			"file":       o.File != nil,
			"metadata":   o.Metadata,
			"build_id":   o.BuildID,
			"compile_id": o.CompileID,
		},
	})
}
1105590
func WithLogging(logger *log.Logger) SendDecorator {
	return func(s Sender) Sender {
		return SenderFunc(func(r *http.Request) (*http.Response, error) {
			logger.Printf("Sending %s %s", r.Method, r.URL)
			resp, err := s.Do(r)
			if err != nil {
				logger.Printf("%s %s received error '%v'", r.Method, r.URL, err)
			} else {
				logger.Printf("%s %s received %s", r.Method, r.URL, resp.Status)
			}
			return resp, err
		})
	}
}
906913
func (ctx *Context) ToJSON(v interface{}) ([]byte, error) {
	b := bytes.NewBuffer(nil)
	enc := ffjson.NewEncoder(b)
	err := enc.Encode(v)
	return b.Bytes(), err
}
160880
func (dm *DocumentMapping) UnmarshalJSON(data []byte) error {

	var tmp map[string]json.RawMessage
	err := json.Unmarshal(data, &tmp)
	if err != nil {
		return err
	}

	// set defaults for fields which might have been omitted
	dm.Enabled = true
	dm.Dynamic = true

	var invalidKeys []string
	for k, v := range tmp {
		switch k {
		case "enabled":
			err := json.Unmarshal(v, &dm.Enabled)
			if err != nil {
				return err
			}
		case "dynamic":
			err := json.Unmarshal(v, &dm.Dynamic)
			if err != nil {
				return err
			}
		case "default_analyzer":
			err := json.Unmarshal(v, &dm.DefaultAnalyzer)
			if err != nil {
				return err
			}
		case "properties":
			err := json.Unmarshal(v, &dm.Properties)
			if err != nil {
				return err
			}
		case "fields":
			err := json.Unmarshal(v, &dm.Fields)
			if err != nil {
				return err
			}
		case "struct_tag_key":
			err := json.Unmarshal(v, &dm.StructTagKey)
			if err != nil {
				return err
			}
		default:
			invalidKeys = append(invalidKeys, k)
		}
	}

	if MappingJSONStrict && len(invalidKeys) > 0 {
		return fmt.Errorf("document mapping contains invalid keys: %v", invalidKeys)
	}

	return nil
}
1229807
func (l *Logger) logWithLevel(logLvl LogLevel, data map[string]interface{}) {
	if logLvl < l.logLvl {
		// No log output
		return
	}
	data["level"] = logLvl.String()
	l.globalsL.RLock()
	defer l.globalsL.RUnlock()
	for key, value := range l.globals {
		if _, ok := data[key]; ok {
			// Values in the data map override the globals
			continue
		}
		data[key] = value
	}
	if l.logRouter != nil {
		data["_kvmeta"] = l.logRouter.Route(data)
	} else if globalRouter != nil {
		data["_kvmeta"] = globalRouter.Route(data)
	}

	l.fLogger.formatAndLog(data)
}
1192732
func ParseJSON(js []byte) *Graph {
	// Parse JSON into Go struct
	var descr graphDescription
	err := json.Unmarshal(js, &descr)
	if err != nil {
		return nil
	}
	// fmt.Printf("%+v\n", descr)

	constructor := func() interface{} {
		// Create a new Graph
		net := new(Graph)
		net.InitGraphState()

		// Add processes to the network
		for procName, procValue := range descr.Processes {
			net.AddNew(procValue.Component, procName)
			// Process mode detection
			if procValue.Metadata.PoolSize > 0 {
				proc := net.Get(procName).(*Component)
				proc.Mode = ComponentModePool
				proc.PoolSize = uint8(procValue.Metadata.PoolSize)
			} else if procValue.Metadata.Sync {
				proc := net.Get(procName).(*Component)
				proc.Mode = ComponentModeSync
			}
		}

		// Add connections
		for _, conn := range descr.Connections {
			// Check if it is an IIP or actual connection
			if conn.Data == nil {
				// Add a connection
				net.ConnectBuf(conn.Src.Process, conn.Src.Port, conn.Tgt.Process, conn.Tgt.Port, conn.Metadata.Buffer)
			} else {
				// Add an IIP
				net.AddIIP(conn.Data, conn.Tgt.Process, conn.Tgt.Port)
			}
		}

		// Add port exports
		for _, export := range descr.Exports {
			// Split private into proc.port
			procName := export.Private[:strings.Index(export.Private, ".")]
			procPort := export.Private[strings.Index(export.Private, ".")+1:]
			// Try to detect port direction using reflection
			procType := reflect.TypeOf(net.Get(procName)).Elem()
			field, fieldFound := procType.FieldByName(procPort)
			if !fieldFound {
				panic("Private port '" + export.Private + "' not found")
			}
			if field.Type.Kind() == reflect.Chan && (field.Type.ChanDir()&reflect.RecvDir) != 0 {
				// It's an inport
				net.MapInPort(export.Public, procName, procPort)
			} else if field.Type.Kind() == reflect.Chan && (field.Type.ChanDir()&reflect.SendDir) != 0 {
				// It's an outport
				net.MapOutPort(export.Public, procName, procPort)
			} else {
				// It's not a proper port
				panic("Private port '" + export.Private + "' is not a valid channel")
			}
			// TODO add support for subgraphs
		}

		return net
	}

	// Register a component to be reused
	if descr.Properties.Name != "" {
		Register(descr.Properties.Name, constructor)
	}

	return constructor().(*Graph)
}