Parsing JSON data using Swift

I need assistance with making an API call to the GitHub API in order to retrieve the names of folders within a repository. I'm unsure about how to extract and process the data returned from the API call. Any guidance or help on this matter would be greatly appreciated!

Sample Code:

func processData() {
    let url = URL(string: "https://api.github.com/repos/myrepository/myrepository/contents/folder")!
    let task = URLSession.shared.dataTask(with: url) { (data, response, error) in
        if let error = error {
            print("Error retrieving data: \(error)")
            return
        }

        guard let httpResponse = response as? HTTPURLResponse,
            (200...299).contains(httpResponse.statusCode) else {
                print("Unexpected status code: \(String(describing: response))")
                return
        }

        if let mimeType = httpResponse.mimeType, mimeType == "application/json",
            let data = data,
            let dataString = String(data: data, encoding: .utf8) {
            print("Data retrieved: \(dataString)")
            
            do {
                if let json = try JSONSerialization.jsonObject(with: data, options: []) as? [String: Any] {
                    print(json["name"])
                }
            } catch let error as NSError {
                print("Failed to load JSON data: \(error.localizedDescription)")
            }

        }
    }
    task.resume()
}

Answer №1

If you want to retrieve the names of folders in a repository, take a look at this sample code snippet. It demonstrates how to make a call to GitHub and fetch the list of folders for one of my repositories. Afterwards, it presents the folders in a List.

struct ContentView: View {
    @State var folders: [RepoContent] = []
    
    var body: some View {
        List(folders) { folder in
            Text(folder.name) + Text(" \(folder.type)").foregroundColor(folder.type == "dir" ? .blue : .red)
        }
        .onAppear {
            getRepoFolders(owner: "workingDog", repo: "OWOneCall")
        }
    }

    func getRepoFolders(owner: String, repo: String) {
        
        guard let url = URL(string: "https://api.github.com/repos/\(owner)/\(repo)/contents") else {
            return
        }
        
        let task = URLSession.shared.dataTask(with: url) { (data, response, error) in
            if let error = error {
                print("Error with fetching repos: \(error)")
                return
            }
            
            guard let httpResponse = response as? HTTPURLResponse,
                  (200...299).contains(httpResponse.statusCode) else {
                print("Error with the response, unexpected status code: \(String(describing: response))")
                return
            }
            
            if let data = data {
                do {
                    let response = try JSONDecoder().decode([RepoContent].self, from: data)
                    self.folders = response
                } catch {
                    print("\n error: \(error)\n")
                }
            }
        }
        task.resume()
    }
    
}

// MARK: - RepoContent
struct RepoContent: Identifiable, Codable {
    let id = UUID()
    let name, path, sha: String
    let size: Int
    let url, htmlURL: String
    let gitURL: String
    let downloadURL: String?
    let type: String
    let links: Links

    enum CodingKeys: String, CodingKey {
        case name, path, sha, size, url, type
        case htmlURL = "html_url"
        case gitURL = "git_url"
        case downloadURL = "download_url"
        case links = "_links"
    }
}

// MARK: - Links
struct Links: Codable {
    let linksSelf: String
    let git: String
    let html: String

    enum CodingKeys: String, CodingKey {
        case linksSelf = "self"
        case git, html
    }
}

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Tips on filtering an array in a JSON response based on certain conditions in Angular 7

Looking to extract a specific array from a JSON response based on mismatched dataIDs and parentDataIDs using TypeScript in Angular 7. { "data":[ { "dataId":"Atlanta", "parentDataId":"America" }, { "dataId":"Newyork", ...

Obtain a specialized field from JSON using VB6

After downloading the VB-JSON, VB6 JSON Parser Class Library, I've been attempting to extract a specific field from a JSON data structure without success. Could someone point out what I might be doing wrong? My code is as follows: Dim p As Object Se ...

What could be the reason my Ruby class is not converting to json?

I'm having trouble figuring out why my basic Ruby object isn't converting to JSON. >irb > require 'json' class User attr_accessor :name, :age def initialize(name, age) @name = name @age = age end end u1 = User.ne ...

What is the best method for extracting a JSON datetime string in Python?

When making a call from Python to a remote API, the returned data is in JSON format. To parse this data, I use the json module with json.loads(). The issue I am facing pertains to dates - the system I am calling returns the date formatted as follows: /Dat ...

Tips for pinpointing a particular item within a JSON document

I am struggling with how to manipulate my JSON file using JavaScript. Each object in the array is associated with an ID, and I want to be able to target specific objects based on their position in the array. For example, how can I append object[1] from arr ...

Leveraging JSON in Play 2

Currently, I am working on developing a straightforward application that allows me to manage different users by creating, reading, updating, and deleting their information. Initially, I set up a basic UI-based view, controller, and model which are function ...

Basic JQ operations: Removing null values and converting text to lowercase

Here is an example of input: [{ "self": "link", "id": "18900", "name": "AUDI", "releaseDate": "2015-12-11" }, { "self": "link", "id": "18900", "name": "FORD", "releaseDate": "2015-12-11" }] This would be the sample ...

Consolidate all data connected to the specified key from a JSON dataset

Looking at the json string presented below [{"_id":"9/17/2015","amt1":0,"amt2":13276.5},{"_id":"9/18/2015","amt1":8075,"amt2":6445.5}] The expected outcome is: [{"_id": ["9/17/2015", "9/18/2015"], "amt1": [0, 8075], "amt2": [13276.5, 6445.5]}] Is there ...

JavaScript Error - Value Not Assigned

I'm having trouble formatting a graph in my code. I keep encountering an undefined error when using console.log to output the data. Here's the snippet of my code: $(document).ready(function () { var graphData = new Array(); $.getJSON("ds ...

extract the field name from the json object

I need to send coordinates to the Google Maps API, but I'm struggling to remove the field name from my JSON object before sending the parameters. Object {TempPoints: "{lat: 51.478,lng: -3.192},{lat: 51.478,lng: -3.192…{lat: 51.47840998047034,lng: - ...

Avoid including newline characters in the string returned from a curl response

I'm facing some challenges in grasping the concept of avoiding interpolation of escape characters in strings, especially those retrieved from a curl response. The data I am receiving looks like this: {"foo":"bar\r\nbaz"} When executing cur ...

The Jersey proxy client is unable to properly deserialize the JSON response into the classes generated by RAML

I have used the raml-to-jaxrs maven plugin (version 2.1.1-SNAPSHOT) to generate classes from this RAML file and I call the service using a Jersey proxy client as shown below: Client client = ClientBuilder.newClient(); Logger logger = Logger.getLogger(getC ...

The Android value with the type java.lang.String cannot be transformed into a JSONArray

My project uses WCF to retrieve records from a database and returns them in JSON format as shown below: {"GetNotesResult":"[{\"ID\":1,\"Title\":\"Note 1\",\"Content\":\"Hello Vu Chien Thang\",\"Create ...

How to parse JSON in JavaScript/jQuery while preserving the original order

Below is a json object that I have. var json1 = {"00" : "00", "15" : "15", "30" : "30", "45" : "45"}; I am trying to populate a select element using the above json in the following way. var selElem = $('<select>', {'name' : nam ...

Can PHP encode the "undefined" value using json_encode?

How can I encode a variable to have the value of undefined, like in the JavaScript keyword undefined? When I searched online, all I found were results about errors in PHP scripts due to the function json_encode being undefined. Is there a way to represent ...

jQuery AJAX event handlers failing to trigger

It's driving me crazy! I've been using jquery's ajax for years, and I can't seem to figure out why the success, error, and complete events won't fire. The syntax is correct, the service it's calling works fine, but nothing hap ...

What's the deal with receiving [object Object] in my JavaScript JSON document?

When I use console.log(values), it returns "[object Object]" instead of logging the array as expected. This is the code snippet I'm working with: let values = { "coins": 0, "griffinFeathers": 0, "souvenir": 0, "cogs": 0, "cats": 0 ...

The GET method is unable to process the body

I have been utilizing mockoon for creating API simulations. I set up 2 routes with the GET method, each responding with a JSON object. Interestingly, my express app seems to struggle parsing one of the routes. However, the route that includes an array in t ...

Exploring the Benefits of Using JSON in AJAX Requests

Can you help me determine the best way to extract data from a php page using ajax in the form of a json array? Here is an example code snippet: $.ajax({ type: "get", url: "assets/update_cart_user_fstore.php", data: up, cache: false, su ...

Transferring Data from JSON Object to an Array

In my AngularJS Controller, I have the following object: {"team":"1","name":"abc","age":"20"}, {"team":"1","name2":"def","age2":"21"}, {"team":"2","name":"ghi","age":"22"}, {"team":"2","name2":"jkl","age2":"23"}, I am looking to consolidate the items int ...