Thank you Rachel and Paul. You have been a big help, and I can run with
this. I did a quick test, and it works:
import groovy.json.JsonSlurper

String goodJsonString = '''{"menu": {
"id": "file",
"tools": {
"actions": [
{"id": "new", "title": "New File"},
{"id": "open", "title": "Open File"},
{"id": "close", "title": "Close File"}
],
"errors": []
}}}'''

String badJsonString = '''{"menu": {
"id": ,
"tools": {
"actions": [
{"id": "new", "title": "New File"},
{"id": "open", "title": "Open File"},
{"id": "close", "title": "Close File"}
],
"errors": []
}}}'''

//String thisString = badJsonString;
String thisString = goodJsonString;

 try {
    JsonSlurper slurper = new JsonSlurper();
    Map parsedJson = slurper.parseText(thisString);
    //assert parsedJson instanceof Map;

    String idValue = parsedJson.menu.id;
    println("The value of idValue is " + idValue + "\nThe value of
jsonString is \n" + thisString);
    println 'Valid JSON'
  } catch(error) {
    println "Invalid: $error.message"
  }

On Tue, Sep 21, 2021 at 7:52 AM Paul King <pa...@asert.com.au> wrote:

> Yes, I also agree with Rachel's comment about groovyConsole. I hit send
> before seeing her reply.
>
>
> On Tue, Sep 21, 2021 at 9:06 PM Rachel Greenham <rac...@merus.eu> wrote:
>
>>
>>
>> > On 21 Sep 2021, at 11:35, James McMahon <jsmcmah...@gmail.com> wrote:
>> >
>> > Hello. Newbie to Groovy. Have a text string that I need to verify is a
>> representation of valid JSON, or not. What is an effective means to do this
>> in Groovy? I'm having difficulty determining what a method like JSONSlurper
>> will return to me if the string can't be parsed because it is not valid
>> JSON? I've found plenty of examples of results it returns when it works,
>> but nothing yet showing me what it returns when the string isn't valid
>> JSON.
>> > Hope this is a valid way to post such a question. As I said, this is my
>> first time trying this or any Groovy forum. Thanks in advance for any help.
>> -Jim
>> >
>>
>> It doesn’t return a value, it throws groovy.json.JsonException, which is
>> a RuntimeException.
>>
>> groovyConsole is your friend in such times…
>>
>> groovy> import groovy.json.*
>> groovy> def slurp = new JsonSlurper()
>> groovy> def parsed = slurp.parseText("}{")
>>
>> Exception thrown
>>
>> groovy.json.JsonException: Unable to determine the current character, it
>> is not a string, number, array, or object
>>
>> The current character read is '}' with an int value of 125
>> Unable to determine the current character, it is not a string, number,
>> array, or object
>> line number 1
>> index number 0
>> }{
>> ^
>>
>> --
>> Rachel Greenham
>> rac...@merus.eu
>>
>>

Reply via email to