Skip to content

Instantly share code, notes, and snippets.

@prwhite
Created January 20, 2013 09:55
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 prwhite/4577588 to your computer and use it in GitHub Desktop.
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.
@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