0

I'm making a simple JSON loading function in my viewmodel, which retrieves the data from a localized JSON file. However, when I call the function it doesn't seem to find anything at all.

func loadJson() {
        
        guard let url = Bundle.main.url(forResource: "parkson", withExtension: "json") /// For some reason, this can't find the url for the Json file
        else {
            print("ERROR - JSON FILE NOT FOUND")
            print(Bundle.main.urls(forResourcesWithExtension: "json", subdirectory: "Model") ?? "There's nothing here...")
            return
        }
        
        do {
            let data = try Data(contentsOf: url)
            let parkInfos = try JSONDecoder().decode([ParkInfo].self, from: data)
            self.listOfParkInfo = parkInfos
        } catch {
            print("ERROR - FAILED TO LOAD JSON --- \(error.localizedDescription)")
        }
    }

(For reference, the name of the JSON file is parkson.json)

When the function is called, it simply prints the "ERROR - JSON FILE NOT FOUND" from the print statement, but in the next print statement it's just "[]"

"ERROR - JSON FILE NOT FOUND" and "[]"

Not sure what I did wrong, most online tutorials use this same function.

4
  • 2
    You need to provide a lot more information. Is this an iOS app or a Mac app? How did you add the JSON file to your app? Have you tried opening the app bundle from the finder and looking to see if the JSON file is at the root level of the bundle?
    – Duncan C
    Commented Jul 8 at 21:13
  • The function is fine, use Finder and drag and drop the file into your Xcode project (left pannel). Commented Jul 8 at 23:31
  • This is an iOS app. I copy/pasted the JSON data from a document into a regular .swift file, then renamed it and changed its file extension to .json.
    – Thomas Lee
    Commented Jul 9 at 16:08
  • I made a separate .txt file outside of Xcode and converted to a .json, which I transferred to my project and that worked. I'm still curious as to why it doesn't want .json files created within Xcode, though.
    – Thomas Lee
    Commented Jul 9 at 16:23

0

Browse other questions tagged or ask your own question.