UPGRADE YOUR SKILLS: Learn advanced Swift and SwiftUI on Hacking with Swift+! >>

Decoding JSON problem, Day 39 tutorial 6/11

Forums > 100 Days of SwiftUI

@Anas  

Hello! Currently I'm decoding astronaut.json into contentView. I've followed along but I seem to get decoding error: "failed to decode..." in the decoding stage. A bit confused because as far as I know, I've copied all the code in from paul's video. Final output should be: ("(astronauts.count)"). Many thanks :)


import Foundation

struct Astronaut: Codable, Identifiable {
    let id: String
    let name: String
    let description: String 
}

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
    }
}

import SwiftUI

struct ContentView: View {

    let astronauts1 = Bundle.main.decode("astronauts.json")

    var body: some View {

        Text("\(astronauts1.count)")
            .padding()

    }
}

Example JSON

[
    {
        "id": "grissom",
        "name": "Virgil I. \"Gus\" Grissom",
        "description": "Virgil Ivan \"Gus\" Grissom (April 3, 1926 – January 27, 1967) was one of the seven original National Aeronautics and Space Administration's Project Mercury astronauts, and the first of the Mercury Seven to die. He was also a Project Gemini and an Apollo program astronaut. Grissom was the second American to fly in space, and the first member of the NASA Astronaut Corps to fly in space twice.\n\nIn addition, Grissom was a World War II and Korean War veteran, U.S. Air Force test pilot, and a mechanical engineer. He was a recipient of the Distinguished Flying Cross, and the Air Medal with an oak leaf cluster, a two-time recipient of the NASA Distinguished Service Medal, and, posthumously, the Congressional Space Medal of Honor."
    }
    ]

2      

not sure if it matters but my astronauts.json starts and ends with a brace and not a square bracket like yours:

{
    "grissom": {
        "id": "grissom",
        "name": "Virgil I. \"Gus\" Grissom",
        "description": "Virgil Ivan \"Gus\" Grissom (April 3, 1926 – January 27, 1967) was one of the seven original National Aeronautics and Space Administration's Project Mercury astronauts, and the first of the Mercury Seven to die. He was also a Project Gemini and an Apollo program astronaut. Grissom was the second American to fly in space, and the first member of the NASA Astronaut Corps to fly in space twice.\n\nIn addition, Grissom was a World War II and Korean War veteran, U.S. Air Force test pilot, and a mechanical engineer. He was a recipient of the Distinguished Flying Cross, and the Air Medal with an oak leaf cluster, a two-time recipient of the NASA Distinguished Service Medal, and, posthumously, the Congressional Space Medal of Honor."
    }
}

3      

@Anas  

@vtabmow thanks for the response! I've actually just had a look at both video and the project 8 files I've manged to get ahold of, and at first, having brackets there wasn't someting i was aware of before you pointed out! It turns out that pauls video didnt have them there too, I thought that maybe the reason my code wasn't compiling. After checking the source file, they've got brackets there too, and for some reason seems to work, so I've stripped out all the code that's used in future tutorials and using that working one as starting point now. I did remove them once you pointed it out however, seems like that previous project doesn't want to build regardless haha. Thanks again!

2      

Weird. In my limited experience in working with json files, usually when they won't decode it's because I'm missing a comma somewhere or something else is out of place in the json file, but if it's all working in a new project that may not be the case.

3      

@Anas  

Yeah tbh just as confused why it wouldnt work, the working source files i'm using now had identical code.

2      

@Bnerd  

missions.json has an array of items, thus the [ ] at the beggining and at the end. astronauts.json , is not array thus no [] required, if you placed [] in astronauts I guess it won't compile.

1      

TAKE YOUR SKILLS TO THE NEXT LEVEL If you like Hacking with Swift, you'll love Hacking with Swift+ – it's my premium service where you can learn advanced Swift and SwiftUI, functional programming, algorithms, and more. Plus it comes with stacks of benefits, including monthly live streams, downloadable projects, a 20% discount on all books, and free gifts!

Find out more

Sponsor Hacking with Swift and reach the world's largest Swift community!

Archived topic

This topic has been closed due to inactivity, so you can't reply. Please create a new topic if you need to.

All interactions here are governed by our code of conduct.

 
Unknown user

You are not logged in

Log in or create account
 

Link copied to your pasteboard.