Created
January 20, 2013 09:55
-
-
Save prwhite/4577588 to your computer and use it in GitHub Desktop.
For primitive xpath-like functionality built on Apple's NSJSONSerialization. Based on this: http://iphonedevsdk.com/forum/iphone-sdk-development/95463-query-value-from-json-with-a-xpath.html But, it adds the ability to find non-leaf nodes, and it tacks onto NSJSONSerialization as a category.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
@implementation NSJSONSerialization (jsonXpath) | |
+ (NSObject *)objectForPath:(NSString *)jsonXPath container: (NSObject*) currentNode | |
{ | |
if (currentNode == nil) { | |
return nil; | |
} | |
// we cannot go any further | |
if(![currentNode isKindOfClass:[NSDictionary class]] && ![currentNode isKindOfClass:[NSArray class]]) { | |
return currentNode; | |
} | |
if ([jsonXPath hasPrefix:@"/"]) { | |
jsonXPath = [jsonXPath substringFromIndex:1]; | |
} | |
NSString *currentKey = [[jsonXPath componentsSeparatedByString:@"/"] objectAtIndex:0]; | |
NSObject *nextNode; | |
// if dict -> get value | |
if ([currentNode isKindOfClass:[NSDictionary class]]) { | |
NSDictionary *currentDict = (NSDictionary *) currentNode; | |
nextNode = [currentDict objectForKey:currentKey]; | |
} | |
if ([currentNode isKindOfClass:[NSArray class]]) { | |
// current key must be an number | |
NSArray * currentArray = (NSArray *) currentNode; | |
nextNode = [currentArray objectAtIndex:[currentKey integerValue]]; | |
} | |
// remove the currently processed key from the xpath like path | |
NSString * nextXPath = [jsonXPath stringByReplacingCharactersInRange:NSMakeRange(0, [currentKey length]) withString:@""]; | |
if ( [ nextXPath length] == 0 ) | |
return nextNode; | |
// call recursively with the new xpath and the new Node | |
return [NSJSONSerialization objectForPath:nextXPath container: nextNode]; | |
} | |
@end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment