Skip to content

Instantly share code, notes, and snippets.

What would you like to do?
For primitive xpath-like functionality built on Apple's NSJSONSerialization. Based on this: 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];
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.