2011-11-22 25 views
6

我無法用perl解析json對象,我不知道問題是來自json還是我的腳本。這裏是JSON:格式錯誤的JSON字符串,無論數組,對象,數字,字符串還是原子

test.json

{ 
    "count":3, 
    "entries": 
    [ 
     { 
     "id":85, 
     "application":AuditExampleLogin1, 
     "user":admin, 
     "time":"2011-11-22T10:29:37.422Z", 
     "values": 
null 
     }, 
     { 
     "id":87, 
     "application":AuditExampleLogin1, 
     "user":admin, 
     "time":"2011-11-22T10:30:56.235Z", 
     "values": 
null 
     }, 
     { 
     "id":89, 
     "application":AuditExampleLogin1, 
     "user":admin, 
     "time":"2011-11-22T10:33:15.000Z", 
     "values": 
null 
     } 
    ] 
} 

這裏的腳本:
script.pl

#!/usr/bin/perl -w 
use strict; 
use JSON; 
open FILE, 'test.json' or die "Could not open file inputfile: $!"; 
sysread(FILE, my $result, -s FILE); 
close FILE or die "Could not close file: $!"; 
my @json = @{decode_json($result)}; 

最後我得到的錯誤:
錯誤

malformed JSON string, neither array, object, number, string or atom, 
at character offset 86 (before "AuditExampleLogin1,\n...") at  
./script.pl line 7. 

問:誰能告訴我該問題是否是由JSON或我的劇本,什麼未來在這兩種情況下的變化?

FYI json is coming from Alfresco auditing api

+3

AFAIK,這不是有效的JSON,周圍是否缺少值引號。 – Mat

+0

我正在處理完全相同的問題。我對線程作者有一個問題:你如何訪問@json變量?我一直認爲@json是內存中的HASH,但我無法訪問變量或循環。 –

回答

2

它適用於審覈...和管理值被引用。該生產線

my @json = @{decode_json($result)}; 

需要只是

my @json = decode_json($result); 
+0

確實在'application'和'user'值被引用時有效。有沒有辦法讓'perl'在解析JSON時更鬆散,並接受未加引號的字符串? (這將使我不必重寫json)。 – Max

+1

不確定,JSON模塊作者認爲嚴格檢查是一項安全功能。你可能會在代碼戳,JSON :: PP是一個純粹的Perl版本。 –

+5

您正在要求JSON解析器成功解析無效的JSON數據。這種方式就是瘋狂,當然:) –

10

此:

"application":AuditExampleLogin1, 

...是無效的JSON。 AuditExampleLogin1不是數組,對象,數字,字符串或原子。我不知道它應該是什麼,所以我不能告訴你如何改變它。

如果它是一個字符串,那麼你需要把它放在"。另見:JSON Lint

另請參閱:JSON Lint

+0

非常方便,即json validtor。謝謝 – Max