Parsing JSON

Here is my json file and I don't know at all how to print cpu_absolute or assign this value to a variable for example, I tried all crazy Codable things, but still nothing works. Help please


    attributes =     {

        "current_state" = running;

        "is_suspended" = 0;

        resources =         {

            "cpu_absolute" = "24.057";

            "disk_bytes" = 1330569622;

            "memory_bytes" = 2770235392;

            "network_rx_bytes" = 1984559;

            "network_tx_bytes" = 1541909;

            uptime = 2224084;

        };

    };

    object = stats;

}
Answered by Claude31 in 718353022

What do you want to decode, attributes ? What is object ?

To get resources, you should define a Codable struct, that has the same components:

struct Resource {
  var cpu_absolute : String
  var disk_bytes : Int
  var memory_bytes : Int
  var network_rx_bytes : Int
  var network_tx_bytes : Int
}
struct Attributes {
  var current_state : String
  var  is_suspended : Int
  var resource : Resource
}

And use as:

        let data = jsonString.data(using: .utf8, allowLossyConversion: false) // your jsonString 
        let jsonDecoder = JSONDecoder()
        do {
            let attributes = try jsonDecoder.decode(Attributes.self, from: data!)
            let cpu_absolute = attributes.resource.cpu_absolute
print(cpu_absolute)
        } catch {
            print("Decode error", jsonString)
        }
Accepted Answer

What do you want to decode, attributes ? What is object ?

To get resources, you should define a Codable struct, that has the same components:

struct Resource {
  var cpu_absolute : String
  var disk_bytes : Int
  var memory_bytes : Int
  var network_rx_bytes : Int
  var network_tx_bytes : Int
}
struct Attributes {
  var current_state : String
  var  is_suspended : Int
  var resource : Resource
}

And use as:

        let data = jsonString.data(using: .utf8, allowLossyConversion: false) // your jsonString 
        let jsonDecoder = JSONDecoder()
        do {
            let attributes = try jsonDecoder.decode(Attributes.self, from: data!)
            let cpu_absolute = attributes.resource.cpu_absolute
print(cpu_absolute)
        } catch {
            print("Decode error", jsonString)
        }

Your json is not Data nor String

Parsing JSON
 
 
Q