1

I have a json object days:

days = {"available_hours":{ 
    "Monday" : [ ["5:30 am","11:00 am"] , [“1:00 pm","4:00 pm”], ["4:00 pm”,  "9:00 pm"] ]
    "Tuesday" : [ [“2:30 pm","7:50 pm"] ]
    "Friday" : [ [“7:30 am","12:50 pm"], [“4:00 pm","11:59 pm”] ]
}  

and I want to get a list with each day and the available hours as a string.

 ["Monday 5:30 am - 11:00 am, 1:00 pm - 4:00 pm, 4:00 pm - 9:00 pm”, "Tuesday 2:30 pm","7:50 pm",etc ]

I am using this function to precess the data and I am passing each day JSON object:

private func hoursList(shifts: [[String]]) -> String{
    var shiftslist: [String] = []
    var shifttext: String = ""
    for shift in shifts {
        shifttext += "\(shifts[0]) - \(shift[1])"
        shiftslist.append(shifttext)
    }  
    return join(", ", shiftslist)
}

the problem is that I cant pass any day because its not convertible to [[String]]

2
  • your json is invalid. i checked it here.jsonlint.com Commented Aug 21, 2015 at 4:05
  • You are right there was couple of missing (,) . but generally the structure is right Commented Aug 25, 2015 at 22:44

1 Answer 1

1

This worked for me:

   // Int from JSON
func getIntFromJSON(data: NSDictionary, key: String) -> Int {

    let info : AnyObject? = data[key]

    if let info = data[key] as? Int {
        return info
    }

    else {
        return 0

    }

}

// Array from JSON
func getArrayFromJSON(data: NSDictionary, key: String) -> NSArray {

    let info : AnyObject? = data[key]

    if let info = data[key] as? NSArray {
        return info
    }

    else {
        return []

    }

}
//Object from JSON
func getObjectFromJSON(data: NSDictionary, key: String) -> AnyObject {

    let info : AnyObject? = data[key]

    if let info: AnyObject = data[key] {
        return info
    }

    else {
        return []

    }

}
// String from JSON
func getStringFromJSON(data: NSDictionary, key: String) -> String {

    let info : AnyObject? = data[key]
    println(data[key])
    if let info = data[key] as? String {
        return info
    }

    return ""
}

You have to call the function by passing your JSON with the key .

    var available_hours = self.getArrayFromJSON(JSONString as! NSDictionary, key: "available_hours")

    // Passing available_hours to get the values for sub-array
    var Tuesday = self.getStringFromJSON(available_hours as! NSDictionary, key: "Tuesday")
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.