Fetching information from JSON file is unsuccessful

Attempting to retrieve data from a JSON source (). The goal is to extract information about each game including goals, location, and teams. However, the current code implementation seems to be ineffective.

    let url = "http://www.openligadb.de/api/getmatchdata/bl1/2014/15"

    //parsing the URL

    if let JSONData = NSData(contentsOfURL: NSURL(string: url)!) {

        if let json = (try? NSJSONSerialization.JSONObjectWithData(JSONData, options: [])) as? NSDictionary {

             //processing the JSON data

        }
    }

The issue lies in the second if-statement (if let json = (try?...). Assistance would be greatly appreciated.

Code snippet for extracting data from dictionaries:

                    //Team 1 Data
                    if let team1 = object["Team1"] as? NSDictionary {

                            if let name = team1["TeamName"] as? String {
                                print("Name of Team 1: \(name)")
                            }
                            if let logo = team1["TeamIconUrl"] as? String {

                                print("Logo of Team 1: \(logo)")
                            }

                            // Additional processing goes here

                    }

Answer №1

Understanding the structure of your JSON data is key: it begins with an array, not a dictionary.

This array contains dictionaries, each containing an array of dictionaries.

While it may seem complicated at first, simply follow the JSON structure and decode the values correctly based on their types.

In JSON, arrays start with [ and dictionaries start with { (note that this syntax differs from Swift's arrays and dictionaries).

Your code could look something like this:

do {
    let url = "http://www.openligadb.de/api/getmatchdata/bl1/2014/15"
    if let url = NSURL(string: url),
           JSONData = NSData(contentsOfURL: url),
           jsonArray = try NSJSONSerialization.JSONObjectWithData(JSONData, options: []) as? NSArray {
            for object in jsonArray {
                if let goalsArray = object["Goals"] as? NSArray {
                    // Each "goal" is a dictionary
                    for goal in goalsArray {
                        print(goal)
                        if let name = goal["GoalGetterName"] as? String {
                            print("Name: \(name)")
                        }
                        if let ID = goal["GoalID"] as? Int {
                            print("ID: \(ID)")
                        }
                        // And so on...
                    }
                }
            }
    }
} catch {
    print(error)
}

UPDATE: You're getting closer! However, "Team1" should be treated as a dictionary, not an array. :)

Here's the corrected code snippet:

do {
    let url = "http://www.openligadb.de/api/getmatchdata/bl1/2014/15"
    if let url = NSURL(string: url),
        JSONData = NSData(contentsOfURL: url),
        jsonArray = try NSJSONSerialization.JSONObjectWithData(JSONData, options: []) as? NSArray {
        for object in jsonArray {
            if let team1 = object["Team1"] as? NSDictionary {
                if let name = team1["TeamName"] as? String {
                    print("Name Team1: \(name)")
                }
                if let logo = team1["TeamIconUrl"] as? String {
                    print("Logo Team1: \(logo)")
                }
            }
        }
    }
} catch {
    print(error)
}

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

Create a unique custom array by utilizing the data retrieved from the WordPress database using the $wpdb->get_results

I am currently working on transforming the output of a table and using wp_send_json to send it as a JSON response. The data is encoded as expected, but I would like to make some changes to the keys, formatting, and order of the data. I am unsure about how ...

Error encountered: Unable to set Content-Type to JSON in a Spring 2.5.x MVC portlet using annotations and AJAX with jQuery

While attempting to utilize spring 2.5.x DispatcherPortlet with liferay for Ajax usage, I encountered an error. The configuration was done using annotations. The following annotations were used at the class level, Controller code... @Controller @Request ...

A guide to converting JSON data into a Java object

I'm currently facing a challenge while attempting to convert this JSON into a Java object. The struggle lies in the conversion process. { "id": "c01cede4-cd45-11eb-b8bc-0242ac130003", "publisherId": "nintendo ...

The class 'JsonParser' is declared as abstract and cannot be created as an instance

When attempting to create a Kafka consumer in IntelliJ, I encountered an issue while trying to instantiate the JsonParser. The error message states: JsonParser is abstract; cannot be instantiated 0 private static JsonParser jsonParser = new JsonParser() ...

Java: Combining JSON Objects with Another JSON Object

I am working on saving chat history in a JSON Object format, where each conversation is represented by an object containing an array of messages. For example: {"Channel_123":[ {"from":"john","to":"bill", "msg":"Hello", "time":"09:57"}, ...

In Python, extract data from the top level of a JSON file

Looking for assistance with parsing a JSON stored as a string: message = """{"info":{"keyVersion":1,"timestamp":"2020-11-05 20:00:00","encryptedData":"75657374696f6e732068617665207265636 ...

Increasing the PHP memory limit while updating large JSON files can help improve performance and

I am facing an issue with my shared hosting provider regarding the 128Mb memory limit. The problem arises when I try to integrate data from AJAX into a PHP controller, which then accesses a file, parses the new data from AJAX, and updates that file by addi ...

The use of AndroidVolley results in an exception when trying to convert the response into a JSONArray using

Can someone please provide assistance? I am encountering an issue when I try to execute the following code: JSONArray jsonArray = new JSONArray(response); My code keeps jumping to the exception block whenever this line is implemented. I am utilizing the ...

Using Angular 5+ to fetch information from an ASP.NET Core Web API

Having trouble retrieving data from an ASP.NET Core 2.0 Web API with Angular 5+. The steps taken so far are as follows: An ASP.NET Core 2.0 Web API was created and deployed on a server. Data can be successfully retrieved using Postman or Swagger. Using ...

Refine intricate nested list JSON queries

I am currently working with the following data: { "additionalInfo": [], "id": "8d929134-0c71-48d9-baba-28fb5eab92f2", "instanceTenantId": "62f4c8ab6a041c1c090f ...

What is the most efficient way to organize JSON data in a tree structure using JavaScript?

I have a JSON data structure that I need to transform into a different format. The original JSON format: values = an array containing objects that need to be filtered by action === 'commented' comment = an object with the comment, n Tasks, and ...

What is the best way to extract data from a basic JSON response using a fetch request

I am encountering an issue with a simple JSON object in my fetch response. When I attempt to access it, the code gets caught in the catch block. this is my response { "islogin": true } fetch(url, data) .then(res => {console.log(res);retur ...

Difficulty in transferring a PHP variable to an AJAX file through json_encode

Currently working on a multi-phase form where the user progresses through each phase by completing different sections. In the first phase, the user fills out a form that is then submitted to the backend for validation and data computation. Once validated, ...

Storing API information as a JSON file with Python

Within my Python files, there are various functions. In another Python file named sample.py, I will be invoking these functions. Each time a function is called, the details within it should be stored in an external JSON file. For example: def Addtext(T ...

What is the proper way to parse an array of JSON objects?

Here is the data I need help with: var information = [ { "_id": "5e458e2ccf9b1326f11b5079", "xxTitle": "testtttttttttttt", "hhhhhhhhhh": "sssssssss", "xxzzzzzz": null, "oooooooooooooo": "ssssss", "xxDescription": "sssssss", "xxDetails": "ssssssss", "llll. ...

Storing JSON data retrieved from a fetch API request in a JavaScript global variable - a beginner's guide

I have been experimenting with the fetch API and successfully managed to log the fetched data to the console using the then() method. However, I am struggling to store this data in a global variable for later use in vanilla javascript due to the nature of ...

Showing data in a grid format on a webpage

I created a Java program that generates an array list with values such as Hi, Hello, How, Are, You, Me, They, and Them. In addition, I developed a basic controller to convert these values into JSON format and display them on localhost:8090/greeting like t ...

Uncovering the secrets to fetching numerous JSON files asynchronously using JavaScript and JQuery

My goal is to fetch multiple JSON files using JavaScript or jQuery and extract elements named j_name, j_value, and j_sts into sarr[i], rarr[i], and parr[i], respectively. var sarr = new Object; var rarr = new Object; var parr = new Object; //num_json rep ...

I am encountering an issue with my curl POST command as it is

I am currently attempting to make a curl POST request for json-rpc, but I am not receiving any errors when using it. I am unsure of what mistake I may be making as I have been trying to work through it for about an hour now. The specific request I am tryi ...

Tips for improving performance on AJAX-based websites with unreliable networks

During my recent travels, I have come across an issue with the way Ajax constructs websites. While I understand that requesting only necessary pieces of a webpage is efficient for servers, in areas with intermittent or limited signal, sites using this mode ...