I have a file with UTF-8 encoding.
I write a groovy script to load a file with a JSON structure, modify it and save it:
def originPreviewFilePath = "./xxx.json"
//target the file
def originFile = new File(originPreviewFilePath)
//load the UTF8 data file as a JSON structure
def originPreview = new JsonSlurper().parse(originFile,'UTF-8')
//Here is my own code to modify originPreview
//Convert the structure to JSON Text
def resultPreviewJson = JsonOutput.toJson(originPreview)
//Beautify JSON Text (Indent)
def finalFileData = JsonOutput.prettyPrint(resultPreviewJson)
//save the JSONText
new File(resultPreviewFilePath).write(finalFileData, 'UTF-8')
The problem is that JsonOutput.toJson
transforms UTF-8 data to UNICODE. I don't understand why JsonSlurper().parse
can use UTF-8 but not JsonOutput.toJson
?
How to have JsonOutput.toJson
use UTF-8? I need to have the exact inverse of JsonSlurper().parse
In case anyone is still struggling with this, the solution is to disable unicode escaping:
new JsonGenerator.Options()
.disableUnicodeEscaping()
.build()
.toJson(object)
This worked for me in Groovy 3:
StringEscapeUtils.unescapeJavaScript(
JsonOutput.prettyPrint(resultPreviewJson)
)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With