Why does the Groovy JSONBuilder escape slashes in URLs? - json

I am writing a Groovy script that needs to POST JSON to a URL. I have noticed a problem were all elements in my JSON that contains a '/' are changed to '\/' by the JSON Builder. Is there a way to stop this?
This is using Groovy 1.8. Here is a simple example and its output:
def json = new JsonBuilder()
json.reply {
result 'http://google.ie/testing'
}
println json.toString()
Output -> {"reply":{"result":"http:\/\/google.ie\/testing"}}
Thanks

Just had a look, and groovy.json.JsonOuput.toJson(string) encodes forward slash as '\\/'.
You can use toPrettyString and it doesn't do it however:
def json = new groovy.json.JsonBuilder()
json.reply {
result 'http://google.ie/testing'
}
assert json.toPrettyString() == '''{
"reply": {
"result": "http://google.ie/testing"
}
}'''

Why does the Groovy JSONBuilder escape slashes in URLs?
An excerpt of the interesting points made in http://groups.google.com/group/opensocial-and-gadgets-spec/browse_thread/thread/1642ec0bed9b95ba/21956eed23f04e13?pli=1 on this topic:
Arne Roomann-Kurrik: Per the JSON spec, escaping '/' is optional.
Mike Samuel: The solidus is among the set of characters that MAY be escaped so that it is safe to embed the JSON substring </script> in HTML as <\/script>. (Half of this quote is by Andrea Ercolino.)
Kevin Brown: This is primarily due to buggy javascript parsers that treat // as a comment
when it's in a string.

Related

removing leading square brackets from json using groovy

I need a way to remove leading square brackets from a json file. Im doing it in SAP cloud platform integration (CPI). Currently I was thinking of using groovy but can't seem to find a way to do it. Heres the JSON example:
[{
"salesOrderNumber": "1234567",
"orderStatus": "Complete",
"customerPONumber": "7654321",
"soldToID": "ABC",
"soldToName": "CBA"
}
]
Thank you in advance
The Code I used for getting just one element, But I need to get multiple in case there are any.
def Message processData(Message message) {
def body = message.getBody(String.class);
def jsonParser = new JsonSlurper();
def jsonObject = jsonParser.parseText(body);
def json = JsonOutput.toJson(jsonObject[0]);
println(json);
message.setBody(json);
return message;
}
You have a list of objects in json. Remove square brackets means get rid of the list and keep only one element of this list.
Btw, what if there are several or zero elements in the list?
So, your algorithm
parse json
get first element list[0]
serialize result back into json
As a code reference look at this documentation: https://groovy-lang.org/json.html

Escape Newlines in Swift as a Raw String

I have a JSON string in Swift 5 that is like this:
var text = """
{"ops": [{"insert": "Hello World!\n"},{"attributes": {"bold": true},"insert": "bold"},{"insert": "What if the "}, {"attributes": {"italic": true},"insert": "italic"}, {"insert": " text was awesome?\n\n"} ]}
"""
I pass that to a WKWebView where it is parsed with JSON.parse(text) so it can be rendered. At present, the JS complains that it's invalid. But if I manually edit the original string and replace all the \n with \\n, it works.
I need to turn \n into \\n programmatically and come out with a string on the other end.
I've tried this:
let raw = #"\#(text)"#
let ready = raw.replacingOccurrences(of: "\n", with: "\\n")
But it treats the newline characters as characters instead of as raw string elements.
It seems like this should be easy, but I can't see what I'm missing. Any ideas?
I found a solution to this. It isn't necessarily an answer to my question, but it avoids the issue altogether.
Prior to sending the JSON data to the Javascript in the WKWebView, I encode it to a string using Base64 encoding. This eliminates the need to worry about escaping characters and such. It works great. :)

Parsing JSON with backslash node.js

I have this JSON file,
{
"file_paths": {
"PROCESS": "C:\incoming",
"FAILED": "C:\failed"
}
}
I get an error when I try to access PROCESS or FAILED. The error is SyntaxError: Unexpected token i in JSON. It must be due to backslash. How can I access PROCESS or FAILED without editing the JSON file?
You will need to escape the backslash in your JSON String.
If you are building the JSON yourself, you can escape special characters when you build it. OR if you are not, as a post process once you have the JSON file you could do something like sed over it to replace the backslash with an escaped backslash (obviously not the ideal solution).
The reason is because the JSON is not valid do to the \ no being escaped making the reader think the i is trying to be escaped
As J Livengood said, you need to escape backslashes when inside a string. Like so:
var obj = {
"file_paths": {
"PROCESS": "C:\\incoming",
"FAILED": "C:\\failed"
}
}

Escape dots in Groovy GPath

I am using the RestAssured framework in Java, whose documentation contains this note
Note that the "json path" syntax uses Groovy's GPath notation and is not to be confused with Jayway's JsonPath syntax.
I need to validate the following JSON:
"_source": {
"logSource": {
"logger.name": "LogbackLogger",
},
}
And the selectors like
_source.logSource.logger.name or
_source.logSource.logger.name[0] return no result.
I assume this is due to the dot in the logger.name property.
If no escaping is done, logger.name is interpreted as if name was under the logger, which is not true.
How do I correctly escape the dot character in the GPath, so that logger.name is considered as a single property name?
Thanks!
You have a trivial issue.
Just wrap it in between single quote i.e., 'logger.name'
as there is special character.
Here is complete example :
def string = """{ "_source": {
"logSource": {
"logger.name": "LogbackLogger",
}
}
}"""
def json = new groovy.json.JsonSlurper().parseText(string)
println json.'_source'.logSource.'logger.name'

Ruby parse string to json

So I have some json that looks like this, which I got after taking it out of some other json by doing response.body.to_json:
{\n \"access_token\": \"<some_access_token>\",\n \"token_type\": \"Bearer\",\n \"expires_in\": 3600,\n \"id_token\": \<some_token>\"\n}\n"
I want to pull out the access_token, so I do
to_return = {token: responseJson[:access_token]}
but this gives me a
TypeError: no implicit conversion of Symbol into Integer
Why? How do I get my access token out? Why are there random backslashes everywhere?
to_json doesn't parse JSON - it does the complete opposite: it turns a ruby object into a string containing the JSON representation of that object is.
It's not clear from your question what response.body is. It could be a string, or depending on your http library it might have already been parsed for you.
If the latter then
response.body["access_token"]
Will be your token, if the former then try
JSON.parse(response.body)["access_token"]
Use with double quotes when calling access_token. Like below:
to_return = {token: responseJson["access_token"]}
Or backslashes are escaped delimiters and make sure you first parse JSON.