-
Notifications
You must be signed in to change notification settings - Fork 19
/
multiline_json_parser.go
61 lines (39 loc) · 1.01 KB
/
multiline_json_parser.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
package main
import (
"bufio"
"bytes"
"strings"
)
/* Parses a multi-line input to a JSON string
input:
key1: value1 \n
key2: value2 \n
output:
{ "key" : "value",
"key" : "value"
}
*/
func parse_multi_line(multiLineInput string)(string, error){
var result bytes.Buffer
// strip whitespace first
multiLineInput = strings.TrimSpace(multiLineInput)
// get the total amount of lines
totalLines := strings.Count(multiLineInput,"\n")
// assign a reader
reader := bufio.NewReader(strings.NewReader(multiLineInput))
// start constructing the JSON string
result.WriteString("{")
for lineCount := 0; lineCount <= totalLines; lineCount++ {
line, err := (reader.ReadString('\n'))
if err != nil {
break
} else {
kvPair := strings.Split(line, ": ")
result.WriteString("\"" + kvPair[0] + "\" : \"" + strings.Trim(kvPair[1],"\n") + "\",")
}
}
// loose the last "," and close with a "}"
result.Truncate(int(len(result.String())-1))
result.WriteString("}")
return result.String(), nil
}