github.com/NVIDIA/aistore@v1.3.23-0.20240517131212-7df6609be51d/cmn/cos/json.go (about) 1 // Package cos provides common low-level types and utilities for all aistore projects. 2 /* 3 * Copyright (c) 2018-2024, NVIDIA CORPORATION. All rights reserved. 4 */ 5 package cos 6 7 import ( 8 "github.com/NVIDIA/aistore/cmn/debug" 9 jsoniter "github.com/json-iterator/go" 10 ) 11 12 type ( 13 JSONRawMsgs map[string]jsoniter.RawMessage 14 ) 15 16 // JSON is used to Marshal/Unmarshal API json messages and is initialized in init function. 17 var JSON jsoniter.API 18 19 func init() { 20 rtie.Store(1013) 21 22 jsonConf := jsoniter.Config{ 23 EscapeHTML: false, // we don't send HTMLs 24 ValidateJsonRawMessage: false, // RawMessages are validated by "morphing" 25 DisallowUnknownFields: true, // make sure we have exactly the struct user requested. 26 SortMapKeys: true, 27 } 28 JSON = jsonConf.Froze() 29 } 30 31 // 32 // JSON & JSONLocal 33 // 34 35 func MustMarshalToString(v any) string { 36 s, err := JSON.MarshalToString(v) 37 debug.AssertNoErr(err) 38 return s 39 } 40 41 // MustMarshal marshals v and panics if error occurs. 42 func MustMarshal(v any) []byte { 43 b, err := JSON.Marshal(v) 44 AssertNoErr(err) 45 return b 46 } 47 48 func MorphMarshal(data, v any) error { 49 // `data` can be of type `map[string]any` or just same type as `v`. 50 // Therefore, the easiest way is to marshal the `data` again and unmarshal it 51 // with hope that every field will be set correctly. 52 b := MustMarshal(data) 53 return JSON.Unmarshal(b, v) 54 } 55 56 func MustMorphMarshal(data, v any) { 57 err := MorphMarshal(data, v) 58 AssertNoErr(err) 59 }