Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Parsing Json in Groovy

Tags:

json

groovy

I have a following json string:

[ { 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 },
]

I am trying to parse this using JsonSlurper but getting error:

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

How do I parse it and access the id:'3425'?

like image 463
asp_NewBee Avatar asked Oct 21 '25 04:10

asp_NewBee


1 Answers

Your Json is invalid, you need to use double quote to delimit strings and you also need to put quotes around the keys in your Json like so:

[ { "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 },
]

You can then do:

def ids = new groovy.json.JsonSlurper().parseText( json ).id
assert ids[ 1 ] == '3425'
like image 157
tim_yates Avatar answered Oct 23 '25 22:10

tim_yates