github.com/maruel/nin@v0.0.0-20220112143044-f35891e3ce7e/cmd/nin/json.go (about) 1 // Copyright 2021 Google Inc. All Rights Reserved. 2 // 3 // Licensed under the Apache License, Version 2.0 (the "License"); 4 // you may not use this file except in compliance with the License. 5 // You may obtain a copy of the License at 6 // 7 // http://www.apache.org/licenses/LICENSE-2.0 8 // 9 // Unless required by applicable law or agreed to in writing, software 10 // distributed under the License is distributed on an "AS IS" BASIS, 11 // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 12 // See the License for the specific language governing permissions and 13 // limitations under the License. 14 15 package main 16 17 import ( 18 "os" 19 ) 20 21 func encodeJSONString(in string) string { 22 hexDigits := "0123456789abcdef" 23 out := "" 24 //out.reserve(in.length() * 1.2) 25 for _, c := range in { 26 switch c { 27 case '\b': 28 out += "\\b" 29 case '\f': 30 out += "\\f" 31 case '\n': 32 out += "\\n" 33 case '\r': 34 out += "\\r" 35 case '\t': 36 out += "\\t" 37 case '\\': 38 out += "\\\\" 39 case '"': 40 out += "\\\"" 41 default: 42 if 0x0 <= c && c < 0x20 { 43 out += "\\u00" 44 out += hexDigits[c>>4 : (c>>4)+1] 45 out += hexDigits[c&0xf : (c&0xf)+1] 46 } else { 47 out += string(c) 48 } 49 } 50 } 51 return out 52 } 53 54 // Print a string in JSON format to stdout without enclosing quotes 55 func printJSONString(in string) { 56 //b, _ := json.Marshal(in) 57 b := encodeJSONString(in) 58 _, _ = os.Stdout.WriteString(b) 59 }