Having trouble structuring URL data in JSON format? Look no further! Check out the example source URL provided for guidance

Check out the URL source code here:

I attempted to use this code, but encountered an issue with struct integration.

    struct Weather: Codable {

    let weather : [cos]
    let base: String


    }

struct cos : Codable {

    let main: String

}


    let url = URL(string:  "https://api.openweathermap.org/data/2.5/weather?q=warsaw&appid=5ca98c08c8abd2bf1fdbd601c3cf3d7e")

    override func viewDidLoad() {
        super.viewDidLoad()
        json()
    }


func json() {
         guard let downloadURL = url else {return}
         URLSession.shared.dataTask(with: downloadURL) { (data, response, error) in


            guard let data = data, error == nil, response != nil
                else {
                    print("something went wrong")
                    return                   
            }
            print("downloaded")
            do{
                let downloaded =try JSONDecoder().decode([Weather].self,from: 
                                    data)
                print("success")
                print(downloaded[0].)
            } catch {
                print("error")
           }
        }.resume()    
    }

Answer №1

This excerpt contains only a portion of the data, leaving some decoding work for you 😉

Make sure to carefully analyze the JSON provided. Each dictionary ({}) can be converted into a struct, with values in double quotes considered as String, floating point numbers as Double, integers as Int, and dates starting with 1523... can be decoded into Date using the appropriate date strategy:

let jsonData = """
{"coord":{"lon":21.01,"lat":52.23},"weather":[{"id":800,"main":"Clear","description":"clear sky","icon":"01d"}],"base":"stations","main":{"temp":294.15,"pressure":1012,"humidity":52,"temp_min":294.15,"temp_max":294.15},"visibility":10000,"wind":{"speed":6.7,"deg":90},"clouds":{"all":0},"dt":1523548800,"sys":{"type":1,"id":5374,"message":0.0023,"country":"PL","sunrise":1523504666,"sunset":1523554192},"id":756135,"name":"Warsaw","cod":200}
"""

struct RootStructure : Decodable {
    let coordData: Coordinate,
    let weatherData: [WeatherDetails],
    let baseInfo: String,
    let mainStats: MainDetails,
    let dateTimeValue: Date
}

struct Coordinate : Decodable {
    let latitude, longitude: Double
}

struct WeatherDetails : Decodable {
    let identifier: Int
    let overallCondition, descriptionInfo, iconImage: String
}

struct MainDetails : Decodable {
    let temperature, minTemp, maxTemp: Double
    let airPressure, humidityLevel: Int
}

let jsonInformation = Data(jsonData.utf8)
do {
    let decoder = JSONDecoder()
    decoder.keyDecodingStrategy = .convertFromSnakeCase
    decoder.dateDecodingStrategy = .secondsSince1970
    let decodedResult = try decoder.decode(RootStructure.self, from: jsonInformation)
    print(decodedResult)
} 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

Utilize dynamically generated Java Strings to assign JSON values for effective Karate integration testing in a dynamic manner

For my Karate Integration testing, I am looking to set randomString/randomNumber as Json values instead of hardcoded ones for the payload using the PUT HTTP verb. Additionally, I would like to store these JSON values in a database. ...

What is the best way to create a JSON object and transmit it via a PUT request from a Rails application to the Shopify API?

Starting out with the Shopify API in a Rails app and this is my first API integration. I think I'm missing something really basic that the documentation assumes I already know. Check out the documentation here - I just want to update attributes on a ...

Filtering JSON data by date range in React JS

I have a dataset with JSON data containing ISO dates, and my goal is to filter out entries based on the "date_created" field falling within a specific date range. The time component should be ignored in this comparison, and the original JSON data should re ...

Obtaining a worldwide JavaScript variable through AJAX JSON query

Hello, I have encountered an issue while using this code for my AJAX JSON request. When attempting to make jsonObj a global variable and then console.log() it, the debugger console shows that it is always coming up as undefined. To explain my question fur ...

Javascript promise failing to deliver

As a beginner in the world of JavaScript development, I am excited to be part of the stackoverflow community and have already gained valuable insights from reading various posts. Currently, I am facing an issue where I need to load a file, but due to its ...

Empty nested Map in POST request

I am currently working on a springboot application with a React/Typescript frontend. I have defined two interfaces and created an object based on these interfaces. export interface Order { customer_id: number; date: Date; total: number; sp ...

Tips for fetching data from a Django REST API endpoint and displaying it in a Flutter Dropdown widget

I am currently working on a project that involves using Django REST for the backend with Flutter dropdown widget to display a list of Country states. However, I am facing challenges in getting the list of states to appear in the dropdown menu. Can anyone p ...

When using PHP's `json_encode()`, don't forget to append a "1" at the

While utilizing json_encode in my project, I have encountered an issue that is perplexing. On one particular page where I make an ajax call, the resulting json seems to mysteriously add a 1 to the end of the string. The output of my return string appears ...

What is the best way to transform a JsonWriter into a JsonObject using GSON?

Looking for assistance on converting JsonWriter to JsonObject in GSON without using any predefined object. JsonWriter writer = new JsonWriter(new FileWriter("C:\\Users\\ravr\\Desktop\\outputJSONSChema.json")); ...

The server is unable to receive lists that are included within the JSON object being passed in

Below are the data contracts utilized in the function. public class ResumeSkillsListDataContract : IResumeSkillsListDataContract { public IList<ISkillDataContract> KnownSkillsList { get; set; } public IList<ISkillDataContract> BadSkill ...

Obtain a set of items from a JSON result and transfer them to the database

I have a table that displays object data triggered by a dropdownbox .change function. However, I also need to submit this data to a database. While I can display the data when the dropdown changes, I'm struggling with retrieving the list of objects an ...

Display a JSON object on a web browser

I am trying to display a JSON object on a web browser using HTML. The object is already in a text file and has been properly formatted for readability. My goal is to maintain the same formatting when displaying it on the browser. ...

Accessing embedded JSON data in Javascript: A step-by-step guide

{ "category": [ { "category_id": "1", "category_name": "Top Picks ", "cover_url": "http://www.example.com" }, { "category_id": "2", "category_name": "Latest Releases", "cover_url": "http://www.exa ...

Determine the percentage using jQuery by considering various factors

I am facing an issue with the following code snippet: <script type="application/javascript"> $(document).ready(function () { $("#market_value").on("change paste keyup", function() { var market_value = par ...

Troubleshooting Problems with Ruby Arrays, JavaScript, and JSON

I am facing a challenge with rendering a highcharts plugin in my rails application. I suspect it could be related to the sql queries fetching data from the database and converting them into a ruby array that the javascript code fails to interpret correctly ...

The process of exporting a dataframe to JSON in a particular format

Is there a way to modify the format of a json file exported using a downloadButton in a Shiny App? The current code successfully exports a data frame to json, but I want it to have a different structure. Here's the code that currently works: library(s ...

Guidelines on configuring JsonSerializerOption on a request-specific basis

I have developed a .NET 7 web api with an endpoint that fetches user data. public class User { public Guid? Id { get; set; } public String? Name { get; set; } public Int32? Age { get; set; } public String? HairColor { get; set; } } When th ...

What is the proper way to provide JSON input for a PUT JAX-RS API that accepts data of type Map<Person, Person>?

I am working on a JAX-RS REST endpoint of PUT type where I need to pass a Map to the API. @PUT @Path("/some/path") @Consumes({ MediaType.TEXT_PLAIN, MediaType.APPLICATION_XML, MediaType.TEXT_XML, MediaType.APPLICATION_JSON }) @Produces({ MediaType ...

Is there a way to access an Excel file with JavaScript without relying on the ActiveX control?

Is there a way to access an Excel document using JavaScript code without relying on an ActiveX control object such as shown below: var myApp = new ActiveXObject("Excel.Application"); myApp.workbooks.open("test.xls"); ...

Unable to post form data into database due to Javascript undefined data situation

I've been working on an HTML form that can interact with a PHP API to retrieve client data and then update user stats in a MySQL database. Currently, I am converting the data into a JSON object and using JSON.stringify to create a string for sending ...