How do I parse data from JSON - Hack The Tech - Latest News related to Computer and Technology

Hack The Tech - Latest News related to Computer and Technology

Get Daily Latest News related to Computer and Technology and hack the world.

Saturday, October 28, 2023

How do I parse data from JSON

Added both PHP and Swift tags as I'm not sure if where the issue lies.

I'll using the below to get information from a webpage in swift, but I'm getting a unable to decode message

func loadData() async {
    guard let url = URL(string: "****") else {
        print("Invalid URL")
        return
    }
    do {
        let (data, _) = try await URLSession.shared.data(from: url)
        if let decodedResponse = try? JSONDecoder().decode(Response.self, from: data) {
            print("Load Data 3")
            dims = decodedResponse.dims
        } else {
            print("Unable to decode")
            print(String(data: data, encoding: .utf8) ?? "")
        }
    } catch {
        print("Invalid data")
    }
}

The php code on the page its calling is

    $sql = "SELECT name,id FROM `DIMs` ORDER BY dimType ASC, released DESC, name ASC LIMIT 2";
    $q = $pdo->prepare($sql);
    $q->execute();
    if($q->errorCode() != 0) {
        $errors = $q->errorInfo();
        echo($errors[2]);
    }
    foreach ($q->fetchAll() as $row) {
        $dims[] = array('id' => $row['id'], 'name' => $row['name']);
    }
    
    echo(json_encode($dims));

Which when viewed in the browser gives me

[{"id":124,"name":"25th Anniversary"},{"id":126,"name":"Angoramon BE"}]

And when printing the decodedResponse I get the same as viewing it in the browser.

I've been following the tutorial at the below link and trying to modify for my requirements. It works fine if I use what's in the tutorial

https://www.hackingwithswift.com/books/ios-swiftui/sending-and-receiving-codable-data-with-urlsession-and-swiftui



source https://stackoverflow.com/questions/77376266/how-do-i-parse-data-from-json

No comments:

Post a Comment