Skip to content

Instantly share code, notes, and snippets.

@haikusw
Forked from chriseidhof/YamlToJSON.swift
Created August 6, 2021 06:23
Show Gist options
  • Save haikusw/eb629d31e0fcdb28263258ff7ec94502 to your computer and use it in GitHub Desktop.
Save haikusw/eb629d31e0fcdb28263258ff7ec94502 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))
}
}
}
@haikusw
Copy link
Author

haikusw commented Aug 6, 2021

https://gist.github.com/helje5 commented:

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