Parsing a JSON array into a NSDictionary
ios5, json, nsdictionary, objective-c
Solution
The brackets means the Json data there are in an array. You can parse it as following
NSArray *alertArray = [json objectForKey:@"alerts"];
now you should loop through all alerts and parse them (in your case it's only 1, but it could be more in another json string):
//parse each alert
for (NSDictionary *alert in alertArray ){
NSString* description = [alert objectForKey:@"description"];
//etc...
}
Problem
I'm working with the Weather Underground API to make an app and I've hit a snag while parsing the block relating to severe alerts. The JSON uses key-value pairs that have sub key value pairs -- which haven't been a problem for me, as I can make subsequent NSDictionaries out of those -- but the entry for severe alerts has proven problematic. See below: ``` "alerts": [ { "type": "WAT", "description": "Flash Flood Watch", "date": "3:13 PM EDT on April 28, 2012", "date_epoch": "1335640380", "expires": "8:00 AM EDT on April 29, 2012", "expires_epoch": "1335700800", "message": "\u000A...Flash Flood Watch in effect through Sunday morning...\u000A\u000AThe National Weather Service in Charleston has issued a\u000A\u000A* Flash Flood Watch for portions of northeast Kentucky... (Note: I trimmed this for length's sake), "phenomena": "FF", "significance": "A" } ] ``` The "alerts" pair differs from others I've been able to parse because it has this [ ] bracket surrounding the sub-values and I'm not sure how to clear it so I can access the subvalues. In the other examples I've been able to parse, it only has the { } brackets, and not both the { } and [ ] brackets. For reference, the brackets are always present -- even when there are no severe weather alerts... in that instance the "alerts" pair returns the brackets [ ] with no sub-pairs present. Is there a way I can remove the [ ] brackets from the NSDictionary, or otherwise ignore them? Any advice would be appreciated! For reference and troubleshooting help, here's how I'm parsing the rest of the JSON document successfully: 1) Create an NSDictionary from the raw JSON ``` //Process Weather Call NSError* error; NSDictionary* json = [NSJSONSerialization JSONObjectWithData:responseData options:kNilOptions error:&error]; ``` 2) Create subsequent dictionaries for nested json pairs ``` NSDictionary *current_observation = [json objectForKey:@"current_observation"]; ``` 3) Assign values ``` NSString* weather; weather = [current_observation objectForKey:@"weather"]; ``` So the end result would be a string that says "Partly Cloudy" or something, along with numerous related weather values that I haven't shown. These parse successfully because they only have the scope brackets { }, and not the [ ] brackets.