How to adjust string into item in JSON structure

My code is validating input json using JSONSchema.isvalid
If it is not valid, code takes string returned by JSONSchema.diagnose and it should return that string as json containing error.
The code looks like this:

diagnosis = JSONSchema.diagnose(dict, schema)
jsonToReturn = JSON3.read("""{"error":"$diagnosis"}""")

But diagnosis variable could contain string as below:

Validation failed:
path:         [configuration][maxModelComplexity]
instance:     0
schema key:   minimum
schema value: 1

In such case, JSON3.read throws error:

ArgumentError: encountered unescaped control character in json: '\n'

So I modified JSON3.read as:

jsonToReturn = JSON3.read("""{"error":"$(replace(diagnosis, "\n" => "\\\\n"))"}""")

That works well for the validation error described above, however, error string could be more complicated:

Validation failed:
path:         [configuration][inSample]
instance:     Any[Dict{String,Any}("to" => "2021-01-07T11:12:32.070Z","from" => "2021-01-07T11:12:32.070Z")]
schema key:   type
schema value: object

In such case, code with replace(diagnosis, “\n” => “\\n”) is insufficient and I am getting error:

ArgumentError: invalid JSON at byte position 110 while parsing type JSON3.Object: ExpectedComma
       Any[Dict{String,Any}("to" => "2021-01-07T11:12:3

Is there some generic string function I could use to convert input string (validation failure explanation) into string I could use in JSON3.read (instead that simple replace call)?

Thank you.

I think the issue is that you have quotes inside your converted string. So JSON looks like:

{"error":"Any[Dict{String,Any}("to" => "2021-01-07T11:12:32.070Z","from" => "2021-01-07T11:12:32.070Z")]"}
                               ^  ^    ^ ....etc

Maybe try a replace(diagnosis, "\"" => "\\\"")?

Thank you, yes, that solves the situation. I need escaping both \n and " character.
However, I still wonder whether there may be lurking some other characters I don’t see yet lurking validation testing.
Isn’t there some generic JSON string function which would adjust this without me worrying about other escape cases?

Not that I know of, but I don’t know the JSON utils very well, so I’m not a good source.