Dany5
Dany5

Reputation: 3

How to load JSON files to swift playgrounds?

I want to load JSON file to swift playground in two type, but it seems a bit confusing because after adding the astronaout.json file (in the first line) it gives the error "top level statement cannot begin with a closure expression", I don't know how to fix it, 2.error is missions. json file (on line 3) 'consecutive statements on a line must be separated by ";".

Any idea how to fix that?

missions.json*

I can’t show the whole code of this files cuz it’s 369 line*

Astronaut.json*

And here is the bundle-decodable code;

import Foundation

extension Bundle {
  func decode(_ file: String) -> [String:    Astronaut] {
      guard let url = self.url(forResource: file, withExtension: nil) else {
        fatalError("failed to locate \(file) in bundle")
     }
      
    guard let data = try? Data(contentsOf:   url) else {
          fatalError("failed to load \(file) from bundle")
    }
    
    let decoder = JSONDecoder()
    
    guard let loaded = try?  decoder.decode([String: Astronaut].self, from: data) else {
        fatalError("failed to decode \(file)     from bundle")
    }
     return loaded
        }
     }

Upvotes: 0

Views: 711

Answers (1)

Joakim Danielson
Joakim Danielson

Reputation: 51892

First you need to add your json files as resources and not source code files to the playground.

  • Go to the Project Navigator (Cmd-1)
  • Click on the top folder to expand it if it's not already expanded
  • Select the "Resources" folder and choose File->Add Files to "Resources"... (Opt-Cmd-A) and then select the file(s)

In the playground you access the files using the Bundle class, there are several ways, one is

if let url = Bundle.main.url(forResource: "missions", withExtension: "json"), 
    let data = try? Data(contentsOf: url) {
    // decode data object
}

Upvotes: 2

Related Questions