我在从文本文件中获取Json Objects并能够在javascript函数中使用它们时遇到问题。但是,如果只有一个Json对象,它就可以工作。然后,当我开始拥有多个Json对象时,它会给出错误:Uncaught SyntaxError: Unexpected token [
以下是我的代码:
的iOS
NSString *post = @"";
NSDictionary *firstJsonDictionary = [NSDictionary dictionaryWithObjectsAndKeys:@"1025", @"DateandTime", logString, @"Description", [self getLogTypeName:(LOGS)level], @"LoggingLevel", nil];
NSMutableArray *arrayTest = [[NSMutableArray alloc] init];
[arrayTest addObject:firstJsonDictionary];
NSData *jsonData2 = [NSJSONSerialization dataWithJSONObject:arrayTest options:NSJSONWritingPrettyPrinted error:nil];
NSString *jsonString = [[NSString alloc] initWithData:jsonData2 encoding:NSUTF8StringEncoding];
post = [NSString stringWithFormat:@"Message=%@", jsonString];
NSLog(@"Post Data: \n%@", post);
NSData *postData = [post dataUsingEncoding:NSASCIIStringEncoding allowLossyConversion:YES];
NSString *postLength = [NSString stringWithFormat:@"%d", [postData length]];
NSURL *logURL = [NSURL URLWithString:@"TestPHP.php"];
NSMutableURLRequest *logRequest = [NSMutableURLRequest requestWithURL:logURL];
[logRequest setHTTPMethod:@"POST"];
[logRequest setValue:postLength forHTTPHeaderField:@"Content-Length"];
[logRequest setValue:@"application/x-www-form-urlencoded" forHTTPHeaderField:@"Content-Type"];
[logRequest setHTTPBody:postData];
NSURLConnection *logConnection = [[NSURLConnection alloc] initWithRequest:logRequest delegate:self];
PHP
$file = 'testingFile.txt';
// Open the file to get existing content
$current = file_get_contents($file);
if (isset($_POST['Message'])) {
// Append a new person to the file
$current .= $_POST['Message'] . PHP_EOL;
// Write the contents back to the file
file_put_contents($file, $current);
} else {
$Contents = file_get_contents($file);
echo $Contents;
}
的Javascript
function GetLoggingData() {
$.get("../ISOSEC/logging/TestPHP.php", function(data){
$.each($.parseJSON(data), function(idx, obj) {
console.log(obj.DateandTime);
console.log(obj.LoggingLevel);
console.log(obj.Description);
AddLog(obj.DateandTime, obj.LoggingLevel, obj.Description);
});
});
}
TEXTFILE
[
{
"DateandTime" : "1025",
"LoggingLevel" : "ERROR",
"Description" : "Test"
}
]
[
{
"DateandTime" : "1025",
"LoggingLevel" : "ERROR",
"Description" : "Test"
}
]
如果有人能够解释我做错了什么会非常棒。 先谢谢你。
答案 0 :(得分:1)
这就是你制作数组的方法
[
{
"DateandTime" : "1025",
"LoggingLevel" : "ERROR",
"Description" : "Test"
},
{
"DateandTime" : "1025",
"LoggingLevel" : "ERROR",
"Description" : "Test"
}
]
答案 1 :(得分:1)
问题是你的字符串不是有效的Json字符串。 如果您像这样修改字符串,它应该可以工作:
[
{
"DateandTime": "1025",
"LoggingLevel": "ERROR",
"Description": "Test"
},
{
"DateandTime": "1025",
"LoggingLevel": "ERROR",
"Description": "Test"
}
]
你还需要调整一下你的代码,因为你得到的结构有点不同。
此外,当您要验证Json文件时,可以使用JSonLint.