Skip to content

Instantly share code, notes, and snippets.

@chriseidhof
Created June 11, 2021 12:13
Show Gist options
  • Save chriseidhof/7b821f72320ef34bc653fb612305c5de to your computer and use it in GitHub Desktop.
Save chriseidhof/7b821f72320ef34bc653fb612305c5de to your computer and use it in GitHub Desktop.
import SwiftUI
import Yams
extension String {
var yamlToJSON: String {
do {
guard let parsed = try Yams.load(yaml: self) else { return "" }
let data = try JSONSerialization.data(withJSONObject: parsed, options: [.sortedKeys, .prettyPrinted])
return String(decoding: data, as: UTF8.self)
} catch {
return "\(error)"
}
}
}
@main
struct YamlToJSONApp: App {
var body: some Scene {
WindowGroup {
ContentView()
}
}
}
struct ContentView: View {
@State var input = ""
var body: some View {
HSplitView {
TextEditor(text: $input)
TextEditor(text: .constant(input.yamlToJSON))
}
}
}
@helje5
Copy link

helje5 commented Jun 11, 2021

As a swift-sh script:

#!/usr/bin/swift sh

import Foundation
import Yams // @jpsim

guard CommandLine.arguments.count > 1 else {
    print("usage: tool file.yaml [file.json]")
    exit(42)
}

do {
    let input  = try String(contentsOfFile: CommandLine.arguments[1])
    let parsed = try Yams.load(yaml: input) ?? [:]
    let data   = try JSONSerialization
         .data(withJSONObject: parsed, options: [.sortedKeys, .prettyPrinted])
    
    if CommandLine.arguments.count > 2 {
        try data.write(to: URL(fileURLWithPath: CommandLine.arguments[2]))
    }
    else if let output = String(data: data, encoding: .utf8) {
        print(output)
    }
    else if !data.isEmpty {
        print("Could not convert data?!")
        exit(44)
    }
}
catch {
    print("Errors happen:", error)
    exit(43)
}

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment