Skip to content

Instantly share code, notes, and snippets.

@CreatureSurvive
Last active November 8, 2018 04:53
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save CreatureSurvive/75faeb943b8951ced44ed28cde227e95 to your computer and use it in GitHub Desktop.
Save CreatureSurvive/75faeb943b8951ced44ed28cde227e95 to your computer and use it in GitHub Desktop.
object from json keypath
/*
* usage:
* [self objectForKeypath:@"someKey.3.someNestedKey.2" inJSON:myJSONObject];
*/
- (id)objectForKeypath:(NSString *)keypath inJSON:(NSData *)json {
if (!keypath || !json) {return nil;}
__block NSInteger depth = 0;
NSArray *keys = [keypath componentsSeparatedByString:@"."];
id result = [NSJSONSerialization JSONObjectWithData:json options:kNilOptions error:nil];
id (^objectAtPath)(NSString *, id) = ^id(NSString *path, id collection) {
if (collection) {
depth++;
if ([collection isKindOfClass:[NSDictionary class]]) {
return [(NSDictionary *)collection objectForKey:path];
}
else if ([collection isKindOfClass:[NSArray class]]) {
return [(NSArray *)collection objectAtIndex:[path integerValue]];
}
}
return nil;
};
while (depth < keys.count) {
if (!result) { return nil; }
result = objectAtPath(keys[depth], result);
}
return result;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment