Skip to content

Instantly share code, notes, and snippets.

@dk949
Created July 24, 2022 19:43
Show Gist options
  • Save dk949/60077566b5ee3f83d15957619412fa2e to your computer and use it in GitHub Desktop.
Save dk949/60077566b5ee3f83d15957619412fa2e to your computer and use it in GitHub Desktop.
convert yaml to json
/+dub.json:
{
"authors": ["dk949"],
"copyright": "Copyright © 2022, dk949",
"dependencies": {"dyaml": "~>0.9.0"},
"description": "Convert yaml to json",
"license": "MIT",
"name": "yaml2json"
}
+/
// Compile with `dub build yaml2json.d --single`
// To run, either pipe yaml into the executable or pass name of the file as the first argument
import dyaml, std;
string loc(Mark m){
return m.name ~ ":" ~ m.line.to!string ~ ":" ~ m.line.to!string;
}
JSONValue toJson(Node n) {
final switch (n.type) {
case NodeType.null_: return JSONValue(null);
case NodeType.boolean: return JSONValue(n.as!bool);
case NodeType.integer: return JSONValue(n.as!ulong);
case NodeType.decimal: return JSONValue(n.as!real);
case NodeType.string:
case NodeType.timestamp: return JSONValue(n.as!string);
case NodeType.sequence:
JSONValue output = JSONValue(string[].init);
foreach (Node node; n)
output.array ~= toJson(node);
return output;
case NodeType.mapping:
JSONValue output = JSONValue(string[string].init);
foreach (string key, Node value; n)
output.object[key] = toJson(value);
return output;
case NodeType.binary:
case NodeType.merge: assert(0, "unhandled `" ~ n.type.to!string ~ "` node at " ~ n.startMark.loc);
case NodeType.invalid: assert(0, "invalid node at " ~ n.startMark.name ~ ":" ~ n.startMark.loc);
}
}
int help(string name, int r) {
writeln("Usage: ", baseName(name), " [FILE]");
return r;
}
int main(string[] argv) {
try {
auto f = stdin;
switch (argv.length) {
case 1:
break;
case 2: {
if (argv[1] == "-h" || argv[1] == "--help") {
return help(argv[0], 0);
} else if (!exists(argv[1])) {
stderr.writeln("no such file ", argv[1]);
return 1;
} else {
f = File(argv[1]);
}
break;
}
default:
return help(argv[0], 1);
}
try {
Loader.fromFile(f).load.toJson.toPrettyString.writeln;
return 0;
} catch (Exception e) {
stderr.writeln("Failed to convert to json: ", e.message);
return 2;
}
} catch (Exception e) {
stderr.writeln("Internal error: ", e.message);
return 3;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment