Saving Dictionaries (as .yaml?)

Hello
I’d like to save and read a dictionary without having anything fancy in the dictionary. Mainly everything that is included by a Json and also symbols.
I was reading this post:

and it was suggested that a json stores symbols. but apparently it does not.
Therefore i considered maybe .yaml is a way to go, but i have no clue how to store and read a dictionary as a yaml.

In the Quarks there is the API quarks which helps with handling JSONs.
I post some example code of how to store JSONs. but since they dont store symbols, maybe somebody can help me out here with an idea or solution? Thank you very much!!

~a = (\hello:("world":1));
~path = PathName(thisProcess.nowExecutingPath).parentPath++"something.json";

//as one can see, the string is converting its symbols to strings.
//hello used to be a key as a symbol and world used to be a string
(
~store = {|path, dict|
	var file, json_string;
	file = File(path, "w");
	json_string = JSON.stringify(dict);
	file.write(json_string);
	file.close;
	json_string
};
~string = ~store.(~path, ~a);
~string.postln;
)


//now the json is loaded, but as previously described, the symbols are strings.
~b = JSONFileReader.read(~path);
~b.postln;

The most hassle-free way to save and load most SC objects is with .readArchive and .writeArchive.

search for those here or in the docs, unless you are hellbent on Jason/yaml

Cheers
eddi
https://alln4tural.bandcamp.com

2 Likes

If it’s only about keeping the keys as symbols, you could try the JSONlib quark, which by default converts the JSON object to an Event with symbols as keys.

Another option and a more readable and editable alternative to read/writeArchive is to save the compileString of the dictionary in a file:

File.use(path, "w", { |f| f.write(dict.asCompileString)})

2 Likes

Thanks for the responses.
Cool i didn’t know about .writeArchive. that might come in handy useful for me at some point too.
I guess i will just stick to the JSONlib and remove all strings in my code and replace them with symbols or something. Not the most elegant but I require the readability from the jsons.

I think you just can’t use json files with null values, as Dictionary and Event don’t accept them:

JSON:

{
  "x" : 10,
  "y" : null
}

SC:

a = (x: 10, y: nil)
-> ( 'x': 10 )