Skip to content

Instantly share code, notes, and snippets.

@michaelhenry
Last active April 7, 2018 03:05
Show Gist options
  • Save michaelhenry/d0e625d9d44054e404818bdabefd623d to your computer and use it in GitHub Desktop.
Save michaelhenry/d0e625d9d44054e404818bdabefd623d to your computer and use it in GitHub Desktop.
JSON to YML converter
extension Array where Iterator.Element == Substring {
var ancestors:[String] {
var _tempSelf = self
_tempSelf.popLast()
return _tempSelf.flatMap { $0.stringValue }
}
}
extension String {
static func tab(_ count: Int, spacePerTab:Int = 2) -> String {
let _a = String(repeatElement(" ", count: count * spacePerTab))
return _a
}
}
extension Substring {
var stringValue:String {
return String(describing: self)
}
}
protocol BaseRenderer {
init(JSON:[String:Any])
func render() -> String
}
class YmlRenderer:BaseRenderer {
private var json:[String:Any]
required init(JSON: [String:Any]) {
json = JSON
}
func render() -> String {
var tempNamespaceText = ""
var column = 0
var text = ""
json
.sorted { $0.key < $1.key}
.forEach { kv in
let currentNamespaceText = kv.key
let currentNamespaces = currentNamespaceText.split(separator: ".")
let tempNamespaces = tempNamespaceText.split(separator: ".")
var thisKey = ""
let tempAncestors = tempNamespaces.ancestors
let currentAncestors = currentNamespaces.ancestors
let maxColumn = min(tempAncestors.count, currentAncestors.count)
if currentAncestors != tempAncestors {
// Reset but check the previous namespaces.
column = 0
while (column < maxColumn ) && currentAncestors[column] == tempAncestors[column] {
column += 1
}
}
while column < (currentAncestors.count) {
// Append the parent namespaces
thisKey = currentNamespaces[column].stringValue
text.append("\(String.tab(column))\(thisKey):\n")
column += 1
}
thisKey = currentNamespaces[column].stringValue
text.append("\(String.tab(column))\(thisKey): \(kv.value) \n")
// Update the tempNamespaceText
tempNamespaceText = currentNamespaceText
}
return text
}
}
let keystrings = [
"login.form.name": "Name",
"login.xxx.name": "Name",
"login.form.password": "Password",
"login.form.headerx": "Login",
"login.form.header.xxx.yyy.z.a.b.x.d.s": "Login",
"registration.form.header": "Registration",
"registration.form.name": "Name of the Registrant",
"start.xxxx.yyy.zzzz": "ZZZZ",
"aa.bb.cc.dd.ee.ff.gg.Name": "ZZZZ",
"aa.bb.cc.dd.ee.ff.gg.name": "ZZZZ",
]
let ymlRenderer = YmlRenderer(JSON: keystrings)
print(ymlRenderer.render())
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment