1

I am trying to extract value of "points" element from JSON data using

    NSString* encodedPoints = [apiResponse stringByMatching:@"points:\\\"([^\\\"]*)\\\"" capture:1L];

but there are more than one "points" elements in the JSON data. Plz help me i dont know much about regular expressions. i am getting JSON Data from this link

2
  • i am not sure if you can use mapkit to display directions , as it is against the legal clause of google. please confirm it from someone. Commented Dec 9, 2011 at 12:00
  • But thats what we are doing using there Directions api. right?? Commented Dec 9, 2011 at 12:14

2 Answers 2

1

You should use a JSON scanner.

Ensure that you have the JSON in an NSString, not an NSData.

Here is a method that uses an NSScanner instead of a regular expression:

NSMutableArray *pointList = [NSMutableArray array];
NSString *pointsString;
BOOL success = YES;
NSScanner *scanner = [NSScanner scannerWithString:encodedPoints];

while (YES) {
    success = [scanner scanUpToString:@"points:\"" intoString:nil];
    success = [scanner scanString:@"points:\"" intoString:nil];
    if (success == NO)
        break;
    success = [scanner scanUpToString:@"\"" intoString:&pointsString];
    [pointList addObject:pointsString];
}

// Show results by print lengths of the found points
for (NSString *point in pointList)
    NSLog(@"point length: %i", point.length);

NSLog output:

point length: 22058
point length: 8889
Sign up to request clarification or add additional context in comments.

Comments

0

You should use a JSON parser for this as that would be more correct/idea for dealing with JSON than using a regex which is prone to failure.

8 Comments

JSON parsers are not working because it is giving invalid JSON response
It depends on which JSON parser you are using and where it fails. To my old eyes, the JSON looked good.
I saw the other thread. It seems that they are not generating JSON to consume as JSON but instead for setting some variables in Javascript. You could just use the following to make it proper JSON.
jsonlint.com let me knew what was wrong. A couple of regexs would fix it. The first problem is with keys in a JSON object. It can be fixed by (\w\+)(\:)/"\1"\2/cg regular expression. The second problem is first value which is not escaping certain characters. Apart from that, JSON is correct.
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.