-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathJSONFileWriter.sc
118 lines (97 loc) · 2.37 KB
/
JSONFileWriter.sc
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
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
/*
Ted Moore
www.tedmooremusic.com
November 30, 2019
SuperCollider convenience class for creating a json file. It takes in a dictionary (or nested dictionaries) and converts them to a json file.
*/
JSONWriter {
*new {
arg object, path;
^super.new.init(object,path);
}
init {
arg object, path;
var file = File(path,"w");
var jsonString = this.unpackObject(object);
file.write(jsonString);
file.close;
^nil;
}
unpackObject {
arg object, depth = 0;
var returnString = "{\n";
object.keys.do({
arg key, i;
var item = object[key];
//"key: %\t\titem: %".format(key,item).postln;
//"item class: %\n".format(item.class).postln;
/*returnString = returnString ++ "\n";*/
(depth+1).do({
arg i;
returnString = returnString ++ "\t";
});
returnString = returnString ++ "\"%\":%".format(key,this.item_to_return_string(item,depth));
if(i != (object.keys.size-1),{
returnString = returnString ++ ",\n";
})
});
returnString = "%\n".format(returnString);
depth.do({
arg i;
returnString = returnString ++ "\t";
});
returnString = returnString ++ "}";
^returnString;
}
item_to_return_string {
arg item, depth;
var returnString;
case
{item.isString || item.isKindOf(Symbol)}{
returnString = item.asString.cs;
}
{item.isNumber}{
var return = nil;
case
{item == inf}{return = "inf".asCompileString}
{item == -inf}{return = "-inf".asCompileString}
{return = item.asCompileString};
returnString = return;
}
{item.isSequenceableCollection.and(item.isString.not)}{
returnString = this.unpack_array(item,depth+1);
}
{item.isKindOf(Event).or(item.isKindOf(Dictionary)).or(item.isKindOf(IdentityDictionary))}{
returnString = this.unpackObject(item,depth+1);
}
{item.isKindOf(Boolean)}{
returnString = item.asString;
}
{item.isNil}{
returnString = "null";
}
{
"ERROR: DON'T KNOW WHAT TO DO WITH THIS:".warn;
item.postln;
item.class.postln;
"".postln;
returnString = item.asCompileString;
};
^returnString;
}
unpack_array {
arg array,depth;
var returnString = "[ ";
array.do({
arg item, idx;
returnString = returnString ++ this.item_to_return_string(item,depth);
if(idx < (array.size-1),{
returnString = returnString ++ ", ";
});
});
returnString = returnString ++ " ]";
//returnString.postln;
^returnString;
}
}