Last active
April 20, 2020 08:16
-
-
Save hangst/dff79cefeeaad5892215512c83ca6157 to your computer and use it in GitHub Desktop.
Stringifies Javascript object to YAML
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
function toYAML(src, pad=0, nested_list=false){ | |
function f(i, nested_list, size){ | |
if (i == 0 && !nested_list) return `\r\n${" ".repeat(size)}` | |
else if(i != 0) return `${" ".repeat(size)}` | |
return "" | |
} | |
var tabsize = 2 | |
var dst = "" | |
if(Array.isArray(src)){ | |
src.forEach(function(s, i){ | |
dst += f(i, nested_list, pad + tabsize) | |
dst += `- ${toYAML(s, pad + 2, true)}` | |
}) | |
} | |
else if(typeof(src) == "object"){ | |
Object.keys(src).forEach(function(key, i){ | |
dst += f(i, nested_list, pad + tabsize) | |
dst += `${key} : ${toYAML(src[key], pad + tabsize)}` | |
}) | |
} | |
else dst += `${src}\r\n` | |
return dst | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment