how to extract a json object using swift? - ios

JSON function:
func extract_json(data:NSString){
var parseError: NSError?
let jsonData:NSData = data.dataUsingEncoding(NSASCIIStringEncoding)!
let json: AnyObject? = NSJSONSerialization.JSONObjectWithData(jsonData, options: NSJSONReadingOptions.MutableContainers, error: &parseError)
if (parseError == nil){
if let coupon_list = json as? [String: AnyObject]{
if let coupons = coupon_list["data"] as? [AnyObject]{
for (var i = 0; i < coupons.count ; i++ ){
if let coupon_obj = coupons[i] as? NSDictionary{
let location: AnyObject? = coupon_obj.objectForKey("location")
//the print the value location
println(location)
//I just want to get the number keys before the value of the location
this is my Json object where you can see that
{
brand = "Mang Inasal";
category = (
2
);
desc = "Mang Inasal Salmonella Giveaway";
discount = 50;
"end_date" = 1443369600;
id = 2;
imgs = (
"http://mymegamobile.com/savvy/halo2x.png",
"http://mymegamobile.com/savvy/bar_filter.png",
"http://mymegamobile.com/savvy/bar_mega.png",
"http://mymegamobile.com/savvy/box1.png",
"http://mymegamobile.com/savvy/box2.png"
);
location = {
1435307555 = Baguio;
};
name = "Mang Inasal Halo Halo";
stamp = "2015-09-02 14:04:38";
"start_date" = 1438012800;
}
the result of the object structure is above.
How can I get the value of 1435307555 in my location?

You can do it this way:
let yourObject = location?.objectForKey("165952298") as! String

for (key,value) in coupon_list {
println(key)
}
This way you'll get all keys from the JSON

func extract_json(data:NSString){
var parseError: NSError?
let jsonData:NSData = data.dataUsingEncoding(NSASCIIStringEncoding)!
let json: AnyObject? = NSJSONSerialization.JSONObjectWithData(jsonData, options: NSJSONReadingOptions.MutableContainers, error: &parseError) as! NSDictionary
if (parseError == nil) {
for (var i = 0; i < json.count ; i++ ) {
let location: AnyObject? = ((json)["location"] as! NSDictionary)["1435307555"]
//the print the value location
println(location)
}
}

Related

parsing json into an array in swift 3

I am new on swift and I am getting a json back from a request but I can not parse. I am trying to get the json info and create coordinates to use on mapkit with annotations as well
Below is the json I get back
{
coord = [
{
islocationactive = 1;
latitude = "37.8037522";
locationid = 1;
locationsubtitle = Danville;
locationtitle = "Schreiner's Home";
longitude = "121.9871216";
},
{
islocationactive = 1;
latitude = "37.8191921";
locationid = 2;
locationsubtitle = "Elementary School";
locationtitle = Montair;
longitude = "-122.0071005";
},
{
islocationactive = 1;
latitude = "37.8186077";
locationid = 3;
locationsubtitle = "Americas Eats";
locationtitle = "Chaus Restaurant";
longitude = "-121.999046";
},
{
islocationactive = 1;
latitude = "37.7789669";
locationid = 4;
locationsubtitle = "Cheer & Dance";
locationtitle = Valley;
longitude = "-121.9829908";
}
] }
and my code to try to parse is this
let task = URLSession.shared.dataTask(with: request as URLRequest){
data, response, error in
//exiting if there is some error
if error != nil{
print("error is \(error)")
return;
}
//parsing the response
do {
//converting resonse to NSDictionary
var teamJSON: NSDictionary!
teamJSON = try JSONSerialization.jsonObject(with: data!, options: .mutableContainers) as? NSDictionary
print(teamJSON)
//getting the JSON array teams from the response
let liquidLocations: NSArray = teamJSON["coord"] as! NSArray
//looping through all the json objects in the array teams
for i in 0 ..< liquidLocations.count{
//getting the data at each index
// let teamId:Int = liquidLocations[i]["locationid"] as! Int!
}
} catch {
print(error)
}
}
//executing the task
task.resume()
but not that I try works. I want to get the latitude, longitude and create an annotationn on the map
Thanks for the help
You can try with below code its same as #Niko Adrianus Yuwono but made some changes so you will get teamid as integer
do {
let data : NSData = NSData() // change your data variable as you get from webservice response
guard let teamJSON = try NSJSONSerialization.JSONObjectWithData(data, options: []) as? [String: Any],
let liquidLocations = teamJSON["coord"] as? [[String: Any]]
else { return }
//looping through all the json objects in the array teams
for i in 0 ..< liquidLocations.count{
let teamId: Int = (liquidLocations[i]["locationid"] as! NSString).integerValue
print(teamId)
}
} catch {
print(error)
}
Try this
do {
guard let teamJSON = try JSONSerialization.jsonObject(with: data!, options: []) as? [String: Any],
let liquidLocations = teamJSON["coord"] as? [[String: Any]]
else { return }
//looping through all the json objects in the array teams
for i in 0 ..< liquidLocations.count{
let teamId: Int = (liquidLocations[i]["locationid"] as! NSString).integerValue
}
} catch {
print(error)
}
The key is not to use NSDictionary and NSArray because it's not strongly-typed (Although you can make it strongly-typed too) use Swift's array and Dictionary where you can use [Element Type] for array and [Key: Value] for dictionary

How to handle json error in loop or stop it

I have the following code that populates a UITableView. The end var holds the number of items in the JSON response. I concatenate variable n with the counter i. My problem is that in this case the JSON response carries only two items, Request1 and Request2. When the counter reaches 3 the app crashes because there is no Request3. How can I change my loop to stop when the condition counter > end is met?
let jsonData = try NSJSONSerialization.JSONObjectWithData(urlData!, options: .MutableContainers) as? NSDictionary
var end = jsonData!["num"]!
var i = 0
var n = "Request"
for item in jsonData! {
i++
n = "Request"+String(i)
var result = jsonData![n] as? NSDictionary
if let Name = result!["Name"] as? String
{
Names.append(Name)
print(Name)
}
if let Date = result!["Request_Id"] as? String
{
Dates.append(Date)
print(Date)
}
}
Try the following:
let jsonData = try NSJSONSerialization.JSONObjectWithData(urlData!, options: .MutableContainers) as? NSDictionary
var end = jsonData!["num"]!
var i = 0
var n = "Request"
for item in jsonData! {
i++
// This should do it
if i == end {
break;
}
n = "Request"+String(i)
var result = jsonData![n] as? NSDictionary
if let Name = result!["Name"] as? String
{
Names.append(Name)
print(Name)
}
if let Date = result!["Request_Id"] as? String
{
Dates.append(Date)
print(Date)
}
}
I'm assuming that by counter > end you mean i > end, as it's what seems to make sense to me.
Try starting your counter i with 1 rather than 0 incrementing it at the end of the loop like this:
let jsonData = try NSJSONSerialization.JSONObjectWithData(urlData!, options: .MutableContainers) as? NSDictionary
var end = jsonData!["num"]!
var i = 0
var n = "Request"
for item in jsonData! {
i++;
if(i==end)break;
n = "Request"+String(i)
var result = jsonData![n] as? NSDictionary
if let Name = result!["Name"] as? String
{
Names.append(Name)
print(Name)
}
if let Date = result!["Request_Id"] as? String
{
Dates.append(Date)
print(Date)
}
}
Also you can consider the following way of doing it
let jsonData = try NSJSONSerialization.JSONObjectWithData(urlData!, options: .MutableContainers) as? NSDictionary
var end = jsonData!["num"]!
var i = 0
var n = "Request"
while(i<end) { //since we are iterating on the basis on the number and specific hardcoded keys of jsondata (and not item) we can just use a normal while loop
i++;
n = "Request"+String(i)
var result = jsonData![n] as? NSDictionary
if let Name = result!["Name"] as? String
{
Names.append(Name)
print(Name)
}
if let Date = result!["Request_Id"] as? String
{
Dates.append(Date)
print(Date)
}
}

Append data to multidimensional array (swift)

I'm having a problem with passing data in an multidimensional array.
So this is the Array:
var dataHome:[[String]] = []
And I would like to pass data into it like this:
if let countries_list = json as? NSArray
{
for (var i = 0; i < countries_list.count ; i++ )
{
if let country_obj = countries_list[i] as? NSDictionary
{
println(country_obj)
let countryName = country_obj["country"] as! String
let countryCode = country_obj["code"] as! String
var tempArray:[String] = []
tempArray.append(countryName)
tempArray.append(countryCode)
println(tempArray)
dataHome.append(tempArray)
println(dataHome)
}
}
}
It crashes when I try to pass data into dataHome.append(tempArray)
The array from country_obj is {code = US;country = Amerika;}
Does anybody have an solution ?
Thank's !
EDIT:
the whole function is:
func extract_json(data:NSString){
var parseError: NSError?
let jsonData:NSData = data.dataUsingEncoding(NSASCIIStringEncoding)!
let json: AnyObject? = NSJSONSerialization.JSONObjectWithData(jsonData, options: nil, error: &parseError)
if (parseError == nil)
{
if let countries_list = json as? NSArray
{
for (var i = 0; i < countries_list.count ; i++ )
{
if let country_obj = countries_list[i] as? NSDictionary
{
println(country_obj)
var countryName = country_obj["country"] as! String
var countryCode = country_obj["code"] as! String
println(countryName)
println(countryCode)
var tempArray:[String] = []
tempArray.append(countryName)
tempArray.append(countryCode)
println(tempArray)
dataHome.append(tempArray)
println(dataHome)
}
}
}
}
do_table_refresh();
}
The error is: Thread 3: Breakpoint 2.1
tempArray.append(countryName)

parsing json objects with arrays in swift

I have this JsonResponse:
...id = 7;
levels = (
{
name = "name";
"unique_id" = 23223;
},
{
name = "name";
"unique_id" = d32432;
},
{
name = "name";
"unique_id" = 324;
},
{
name = "name";
"unique_id" = 234;
}
);
I am using this to get result as a dictionary:
var jsonResult = NSJSONSerialization.JSONObjectWithData(data, options: NSJSONReadingOptions.MutableContainers, error: &err) as! NSDictionary
MY question is how can i parse the levels array - iterating the objects and getting the array size
Basically you just loop through them:
if(jsonResult)
{
let levels = jsonResult! as NSDictionary;
for item in levels {
let obj = item as NSDictionary
let name = obj["name"] as NSString;
let uniqueId = obj["unique_id"] as NSNumber;
}
}
I would advise to use type safety as much as you can when using JSON. Here is an (untested) example to show you how you can cast safely the data:
if let levels = NSJSONSerialization.JSONObjectWithData(data, options: NSJSONReadingOptions.MutableContainers, error: &err) as? [[String: AnyObject]] {
for elem in levels {
let name = elem["name"] as? NSString
let uniqueId = elem["unique_id"] as? NSNumber
}
}

json date how to store in array

data = "{\"2\":{\"Systolic_bp\":\"28\",\"Dystolic_bp\":\"29\",\"Weight\":\"22\",\"Height\":\"24\",\"Pulse\":\"26\",\"Temp\":\"25\",\"Respiration\":\"27\",\"BMI\":\"A:1:{s:4:\\\"SPO2\\\";s:1:\\\"1\\\";}\",\"BSA\":\"A:1:{s:4:\\\"SPO2\\\";s:1:\\\"1\\\";}\",\"tcomplients\":\"\",\"drdate\":\"25\\/08\\/2014\",\"medicine\":\"RABEPRAZOLE\",\"drugclass\":\"Tablet\",\"dosage\":\"1\",\"duration\":\"5 day\",\"frequency\":\"\",\"route\":\"Oral\",\"drnotes\":\"\"},\"1\":{\"tcomplients\":\"\",\"drdate\":\"25\\/08\\/2014\",\"medicine\":\"ACECLOFENAC+PARACETAMOL\",\"drugclass\":\"Tablet\",\"dosage\":\"1\",\"duration\":\"5 day\",\"frequency\":\"\",\"route\":\"Oral\",\"drnotes\":\"\"}}";
let jsonData:NSDictionary = NSJSONSerialization.JSONObjectWithData(urlData!, options:NSJSONReadingOptions.MutableContainers , error: &error) as NSDictionary
println(jsonData)
let dat1:NSString = jsonData.valueForKey("status")as NSString
let dat:NSString = jsonData.valueForKey("data") as NSString
if(dat1 == "SUCCESS")
{
// NSLog("Success: %d", jsonData);
var fullName: String = dat
// NSLog(fullName)
//firstName = "vinod"
let fullNameArr = fullName.componentsSeparatedByString(":")
//NSLog(fullName)
firstName = fullNameArr[0]
lastName = fullNameArr[1]
sex = fullNameArr[2]
Dob = fullNameArr[3]
encounter = fullNameArr[4]
consultDR = fullNameArr[5]
// room = fullNameArr[6]
//bed = fullNameArr[7]
//doa = fullNameArr[8]
//wardno = fullNameArr[9]
NSLog(fullNameArr[0])
NSLog(fullNameArr[1])
NSLog(fullNameArr[2])
NSLog(fullNameArr[3])
NSLog(fullNameArr[4])
NSLog(fullNameArr[5])
// NSLog(fullNameArr[6])
// NSLog(fullNameArr[7])
// NSLog(fullNameArr[8])
//NSLog(fullNameArr[9])
tried this not working
let jsonString = "{\"2\":{\"Systolic_bp\":\"28\",\"Dystolic_bp\":\"29\",\"Weight\":\"22\",\"Height\":\"24\",\"Pulse\":\"26\",\"Temp\":\"25\",\"Respiration\":\"27\",\"BMI\":\"A:1:{s:4:\\\"SPO2\\\";s:1:\\\"1\\\";}\",\"BSA\":\"A:1:{s:4:\\\"SPO2\\\";s:1:\\\"1\\\";}\",\"tcomplients\":\"\",\"drdate\":\"25\\/08\\/2014\",\"medicine\":\"RABEPRAZOLE\",\"drugclass\":\"Tablet\",\"dosage\":\"1\",\"duration\":\"5 day\",\"frequency\":\"\",\"route\":\"Oral\",\"drnotes\":\"\"},\"1\":{\"tcomplients\":\"\",\"drdate\":\"25\\/08\\/2014\",\"medicine\":\"ACECLOFENAC+PARACETAMOL\",\"drugclass\":\"Tablet\",\"dosage\":\"1\",\"duration\":\"5 day\",\"frequency\":\"\",\"route\":\"Oral\",\"drnotes\":\"\"}}"
if let jsonData = jsonString.dataUsingEncoding(NSUTF8StringEncoding, allowLossyConversion: false) {
var error: NSError?
if let jsonDict = NSJSONSerialization.JSONObjectWithData(jsonData, options: NSJSONReadingOptions.MutableContainers, error: &error) as? [String:AnyObject] {
let dicKeys = jsonDict.keys.array
for key in dicKeys {
println("\n")
if let subDic = jsonDict[key] as? [String:String] {
let subDicKeys = subDic.keys.array
for sKey in subDicKeys {
println(sKey + " = " + subDic[sKey]! )
}
}
}
} else {
println(false)
}
} else {
println(false)
}

Resources