-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy path09_json.ring
More file actions
61 lines (51 loc) · 1.32 KB
/
09_json.ring
File metadata and controls
61 lines (51 loc) · 1.32 KB
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
59
60
61
/*
09 - JSON Processing
Use Python's json module to parse and generate JSON.
*/
load "python.ring"
py_init()
py_exec("import json")
# ---- Parsing JSON ----
? "=== Parse JSON ==="
jsonstr = '{"name": "Ring", "version": ' + version() + ', "features": ["OOP", "Functional", "Declarative"]}'
py_set("raw", jsonstr)
py_exec("parsed = json.loads(raw)")
parsed = py_get("parsed")
? "Parsed JSON:"
for pair in parsed
if islist(pair) and len(pair) = 2
key = pair[1]
value = pair[2]
if islist(value)
? " " + key + ":"
for item in value
? " - " + item
next
else
? " " + key + ": " + value
ok
ok
next
# ---- Generating JSON ----
? ""
? "=== Generate JSON ==="
# Build a Ring structure, send to Python, dump as JSON
data = [
["language", "Ring"],
["year", 2016],
["tags", ["embedded", "python", "cross-platform"]]
]
py_set("data", data)
py_exec("pretty = json.dumps(data, indent=2, sort_keys=True)")
? py_get("pretty")
# ---- Round-trip ----
? ""
? "=== Round-trip ==="
py_exec("
original = {'pi': 3.14159, 'items': [1, 2, 3], 'nested': {'a': True}}
encoded = json.dumps(original)
decoded = json.loads(encoded)
match = original == decoded
")
? "Encoded: " + py_get("encoded")
? "Round-trip match: " + py_get("match")