How to parse a JSON having no quotes with its KEY string?

3.8k views Asked by At

I want to parse the json output resulting from the following url in SBJSON framework for iOS http://maps.google.com/maps?q=school&mrt=yp&sll=13.006389,80.2575&output=json

while(1);{title:"school - Google Maps",url:"/maps?q=school\x26mrt=yp\x26sll=13.006389,80.2575\x26ie=UTF8\x26hq=school\x26hnear=",urlViewport:false,ei:"RCu3T4eeMqSiiAe7k-yZDQ",form:{selected:"q",q:{q:"school",mrt:"yp",what:"school",near:""},d:{saddr:"",daddr:"",dfaddr:""},geocode:""},

I am using http://www.bodurov.com/JsonFormatter/ to read it online.

In ASIHttpRequest response method I removed while(1); from the response

NSString *responseString = [[request resonseString]substringFromIndex:9]; //to remove while(1)
SBJSONParser * parser = [[SBJSONParser alloc]init];
NSDictionary *jsonDict = (NSDictionary*)[parser objectFromString:responseString];
NSLog(@"%@",jsonDict) // prints null
// [responseString JSONValue] also reports error

I guess JSON key without double quotes is causing problem.

Instead of { "title": "hospital - Google Maps", "urlViewport": false, }, we get { title: "hospital - Google Maps", "urlViewport": false }

Please help me to parse this complex JSON structure returned from Google.

2

There are 2 answers

1
Hejazi On

You need to add the missing quotes to the keys, so try this:

responseString = [responseString stringByReplacingOccurrencesOfString:@"(\\w+)\\s*:" 
                                 withString:@"\"$1\":" 
                                 options:NSRegularExpressionSearch 
                                 range:NSMakeRange(0, [responseString length])];

This should work well with the given JSON string.

2
greg On

This worked better for my case because my values contained times which caused the regular expression in the above answer to match incorrectly.

json = [json stringByReplacingOccurrencesOfString: @"(\\w*[A-Za-z]\\w*)\\s*:"
                                       withString: @"\"$1\":"
                                          options: NSRegularExpressionSearch
                                            range: NSMakeRange(0, json.length)];