Skip to content Search Apps Documentation Source Content Run Reset Eval Playground File Folder Download Copy Actions State String Boolean Number Struct Map Slice Pointer Function Closure Reference Nil Package Type Interface Unknown

Community realm. Read the code first. Community realm, deployed by its author. Read the code before you interact or send coins.

json.gno

1.49 Kb · 78 lines
 1package board
 2
 3import (
 4	"strconv"
 5	"strings"
 6)
 7
 8// jsonString quotes s as a JSON string. Everything outside printable ASCII
 9// is written as a \u escape, so the output is plain ASCII.
10func jsonString(s string) string {
11	var b strings.Builder
12	b.WriteByte('"')
13	for _, r := range s {
14		switch {
15		case r == '"':
16			b.WriteString(`\"`)
17		case r == '\\':
18			b.WriteString(`\\`)
19		case r >= 0x20 && r < 0x7f:
20			b.WriteRune(r)
21		case r > 0xffff:
22			r -= 0x10000
23			writeU16(&b, 0xd800+(r>>10))
24			writeU16(&b, 0xdc00+(r&0x3ff))
25		default:
26			writeU16(&b, r)
27		}
28	}
29	b.WriteByte('"')
30	return b.String()
31}
32
33func writeU16(b *strings.Builder, r rune) {
34	const hex = "0123456789abcdef"
35	b.WriteString(`\u`)
36	b.WriteByte(hex[(r>>12)&0xf])
37	b.WriteByte(hex[(r>>8)&0xf])
38	b.WriteByte(hex[(r>>4)&0xf])
39	b.WriteByte(hex[r&0xf])
40}
41
42func jsonUint(v uint64) string {
43	return strconv.FormatUint(v, 10)
44}
45
46func jsonInt(v int64) string {
47	return strconv.FormatInt(v, 10)
48}
49
50func jsonBool(v bool) string {
51	if v {
52		return "true"
53	}
54	return "false"
55}
56
57// jsonObject joins already-encoded key/value pairs.
58func jsonObject(pairs ...string) string {
59	if len(pairs)%2 != 0 {
60		panic("jsonObject needs key/value pairs")
61	}
62	var b strings.Builder
63	b.WriteByte('{')
64	for i := 0; i < len(pairs); i += 2 {
65		if i > 0 {
66			b.WriteByte(',')
67		}
68		b.WriteString(jsonString(pairs[i]))
69		b.WriteByte(':')
70		b.WriteString(pairs[i+1])
71	}
72	b.WriteByte('}')
73	return b.String()
74}
75
76func jsonArray(items []string) string {
77	return "[" + strings.Join(items, ",") + "]"
78}