2013-04-25 112 views
2

我有以下的JSON字符串:解析JSON在Groovy

[ { id: '123', name: 'bla bla', type: 'Source', isLeaf: true }, 
    { id: '3425', name: 'test test', type: 'Reference', isLeaf: false }, 
    { id: '12678', name: 'tags', type: 'Source', isLeaf: false }, 
] 

我试图分析此使用JsonSlurper但得到的错误:

groovy.json.JsonException: Lexing failed on line: 1, column: 5, while reading 'i', no possible valid JSON value or punctuation could be recognized. 

如何分析它,并访问id:'3425'

回答

4

您的JSON是无效的,你需要使用双引号来分隔字符串,你也需要把周围的按键报价在您的JSON像这样:

[ { "id": "123", "name": "bla bla", "type": "Source", "isLeaf": true }, 
    { "id": "3425", "name": "test test", "type": "Reference", "isLeaf": false }, 
    { "id": "12678", "name": "tags", "type": "Source", "isLeaf": false }, 
] 

那么你可以这样做:

def ids = new groovy.json.JsonSlurper().parseText(json).id 
assert ids[ 1 ] == '3425' 
+0

首先我这么认为,但http://jsonviewer.stack.hu/告诉你,Json是一个有效的。无论如何谢谢你的回应。 – 2013-04-25 14:02:06

+0

我怀疑jsonviewer.stack.hu是错误的。 http://jsonlint.com/ http://en.wikipedia.org/wiki/JSON#Data_types.2C_syntax_and_example – 2013-04-25 14:09:58

+1

@asp_NewBee:如果jsonviewer应用程序说它是有效的,那就错了。 spec(http://json.org/)很清楚。 – 2013-04-25 14:10:27