简体   繁体   English

如何使用“ var abcd =”标头解析json数据

[英]How to parse json data with “var abcd =” header

I'm having problem with parsing json data file on iOS. 我在iOS上解析json数据文件时遇到问题。 This is a sample from the data.json file: 这是来自data.json文件的示例:

var devs = [
{
"ident":"1",
"firstname":"Jan", 
"lastname":"Kowalski", 
"img":"http://www.placekitten.com/125/125", 
"tech":"iOS, HTML5, CSS, RWD",
"github":"placeholder",
"opensource":"1",
"twitter":"placeholder"
},
{
"ident":"2",
"firstname":"WacĹaw", 
"lastname":"GÄsior", 
"img":"http://www.placekitten.com/124/125",
"tech":"Android, Java, Node.js",
"github":"GÄsiorBKR",
"twitter":"wacek5565"
},

and so on. 等等。

With "normal" json files I use: 我使用“普通” json文件:

NSURLResponse *response;
NSError *myError;
NSURLRequest *urlRequest = [NSURLRequest requestWithURL:[NSURL      URLWithString:@"http://somerailsapplication/posts.json"]     cachePolicy:NSURLRequestReloadIgnoringCacheData timeoutInterval:30.0f];
NSData *data = [NSURLConnection sendSynchronousRequest:urlRequest returningResponse:&response error:&myError];
NSDictionary *res = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableLeaves error:&myError];

Unfortunately this solution doesn't work in this case. 不幸的是,这种解决方案在这种情况下不起作用。 Is there any chance to get this working without searching for specific string "var dev=[" and the last "]" in the downloaded data? 是否有机会在下载的数据中不搜索特定字符串“ var dev = [”和最后一个“]”的情况下使此工作正常进行?

The response is javascript, not JSON, so you won't be able to use a JSON parser directly. 响应是JavaScript,而不是JSON,因此您将无法直接使用JSON解析器。 If you can't change the server output, the easiest thing would be to strip the beginning and end of the data, as you suggested. 如果您无法更改服务器输出,最简单的方法就是按照您的建议剥离数据的开头和结尾。 You could also embed the response in an HTML template and evaluate it in a webview, but that seems like a lot of more work. 您也可以将响应嵌入HTML模板中,然后在Webview中对其进行评估,但这似乎还有很多工作要做。

Starting at the point where you've got the data: 从获得数据的那一点开始:

NSData *data = [NSURLConnection sendSynchronousRequest:urlRequest returningResponse:&response error:&myError];
NSMutableString *dataAsString = [[NSMutableString alloc] initWithData:data encoding:NSUTF8StringEncoding];
[dataAsString deleteCharactersInRange:NSMakeRange(0, 11)];
data = [dataAsString dataUsingEncoding:NSUTF8StringEncoding];
NSArray *res = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableLeaves error:&myError];

This turns the data into a string, removes the first 11 characters, turns it back into data, and then parses it as normal. 这会将数据转换为字符串,删除前11个字符,将其转换回数据,然后按常规进行解析。 (I've changed it to NSArray since your data is in an array) (由于您的数据在数组中,因此我将其更改为NSArray)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM