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

只谈情不闲聊 提交于 2019-12-23 13:07:32

问题


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.


回答1:


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)];



回答2:


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.



来源:https://stackoverflow.com/questions/10664028/how-to-parse-a-json-having-no-quotes-with-its-key-string

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!