简体   繁体   中英

Swift Vapor: How to read a JSON file?

I'm using Vapor, the server-side Swift 4 framework for creating web servers. I have a migration that I'd like to apply that reads in from a JSON file; however, most if not all Swift tutorials I see on this indicate using Bundle , which to my knowledge, isn't available when developing server-side swift applications, which means attempts like this don't work:

if let path = Bundle.main.url(forResource: "myFile", withExtension: "json") {
...

This begs the question, given a relative file path, how can I read in a file using server-side Swift?

Silly me. Vapor exposes a DirectoryConfig object from which you can retrieve the working directory of the application. To parse a file, it thus becomes:

let directory = DirectoryConfig.detect()
let configDir = "Sources/App/Configuration"

do {
    let data = try Data(contentsOf: URL(fileURLWithPath: directory.workDir)
        .appendingPathComponent(configDir, isDirectory: true)
        .appendingPathComponent("myFile.json", isDirectory: false))

    // continue processing

} catch {
    print(error)
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM