Re: Misformatting json output

"Nelson, Erick" <Erick.Nelson-NXabUB82sh5Wk0Htik3J/[email protected]>
Newsgroups gmane.comp.lang.groovy.user
Message-ID <BN0PR13MB4760A1944FC45C91EB36B11EE7A29@BN0PR13MB4760.namprd13.prod.outlook.com>
import groovy.json.*

def data = [
  fieldA:[lname:"Smith", fname:"John"],
  fieldB:[age:21, gender:"M"],
  fieldC:12345
]

println JsonOutput.toJson(data)


^^^ this works for me.
Running it produces this…

{"fieldA":{"lname":"Smith","fname":"John"},"fieldB":{"age":21,"gender":"M"},"fieldC":12345}

What is the source of your data look like?
Is fieldC a number or a string?

From: James McMahon <[email protected]>
Date: Monday, June 6, 2022 at 8:36 AM
To: users-GSC0n/0aZo1d/SJB6HiN2Ni2O/[email protected] <users-GSC0n/0aZo1d/SJB6HiN2Ni2O/[email protected]>
Subject: [EXT] Misformatting json output
I am having problems properly formatting Json output to requirements.
I have three fields, similar to this:
fieldA has value {"lname":"Smith", "fname":"John"}
fieldB has value  {"age":"21", "gender":"M"}
fields has value 12345

I put each into an empty Groovy map, result[:] .

I'm required to generate Json output like this:
{
"fieldA": {"lname":"Smith", "fname":"John"},
"fieldB": {"age":"21", "gender":"M"},
"fieldC":"12345"
}

but am instead getting output with double quotes around the { } for fields A and B, like this:
{
"fieldA": "{"lname":"Smith", "fname":"John"}",
"fieldB": "{"age":"21", "gender":"M"}",
"fieldC":"12345"
}

Is there a way I can suppress the surrounding of the values in the map when I create the json?

Currently this is how I process my map to json:

def JsonStr = JsonOutput.prettyPrint(JsonOutput.toJson(result))

which I then write to my outputStream like this:

outputStream.write(JsonStr.getBytes(StandardCharsets.UTF_8))

Thanks in advance for any help.
lmpx.com only provides a reader for public news (NNTP) servers. It is not affiliated with the servers or forums shown here and is not responsible for the content of articles, which is written by their respective authors.