asp_NewBee
asp_NewBee

Reputation: 299

Parsing Json in 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'?

Upvotes: 4

Views: 27709

Answers (1)

tim_yates
tim_yates

Reputation: 171054

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'

Upvotes: 6

Related Questions