Strip backslashes from encoded JSON response - json

Building a Json respose with erlang. First I construct the data in terms and then use jsx to convert it to JSON:
Response = jsx:term_to_json(MealsListResponse),
The response actually is valid JSON according to the validators I have used:
The problem is when parsing the response in the front end. Is there a way to strip the backslashes from the Erlang side, so that the will not appear on the payload response?

The backslashes are not actually part of the string. They're just used when the string is printed as a term - that is, in the same way you'd write it in an Erlang source file. This works in the same way as character escapes in strings in C and similar languages: inside double quotes, double quotes that should be part of the string need to be escaped with backslashes, but the backslashes don't actually make it into the string.
To print the string without character escapes, you can use the ~s directive of io:format:
io:format("~s~n", [Response]).
If you're sending the response over a TCP socket, all you need to do is converting the string to binary with an appropriate Unicode conversion. Most of the time you'll want UTF-8, which you can get with:
gen_tcp:send(MySocket, unicode:characters_to_binary(Response)).

Related

How to escape single quotes in json string? JSON::ParserError Ruby

I'm getting
/json/common.rb:156:in `parse': 783: unexpected token at '' (JSON::ParserError) while trying to parse a json file in ruby. The problem was because there were some single quotes in one of the strings:
parsed = JSON.parse("{
\"key1\":\"value1\",
\"key2\":\"value2\",
\"key3\":12345,
\"key4\":\"''value4''\",
}")
Is there a way to escape the single quotes in the strings without affect words like don't? The json is read from a file using JSON.parse(file.get_input_stream.read) that's why there are \.
The single quotes aren't your problem, your problem is that you have a stray trailing comma:
parsed = JSON.parse("{
\"key1\":\"value1\",
\"key2\":\"value2\",
\"key3\":12345,
\"key4\":\"''value4''\",
}") #--------------------^ This should not be there.
JSON doesn't allow that comma so you don't actually have a JSON file.
You should figure out where the file came from and fix that tool to produce real JSON rather than the "looks mostly like JSON" that is currently being written to the file.

removing backslashes in mule 4 dataweave transformation

I am fetching data from SQL Server Database and transforming it into JSON in Mule 4. My input has a single backslash and converted to double backslashes. I only need a single backslash in my output.
Input example:
abchd\kdgf
Output is:
"abchd\\kdgf"
It should be:
"abchd\kdgf"
Anyone can help with this data weave transformation?
In JSON strings the backslash character is the escape character, and has to be escaped itself to represent a single backlash. That's how JSON works, it is not a Mule issue.
Here single slash treated internally as double slash. Try the dataweave expression like below
payload replace /([\\])/ with ("")
Hope it helps

Change single backslash in R character string to valid JSON string

I have a string in R which escapes quotation marks:
my_text = {\"stim\":[\"platery\",\"denial\",\"generic\"]}
When using cat() I get:
{"stim":["platery","denial","generic"]}
Now my whole string is a JSON string that needs to be parsed and is evaluated invalid by JSONLint. If I copy&paste the cat() version, this is valid a JSON, so I think I just miss some pre-processing here.
I saw this SO post here, and this one, and this really good one, so I tried to replace the single quotation marks with double quotation marks for the JSON parser:
gsub("\\\\", "\\\\\\\\", my_text, fixed=TRUE)
but it did't change my string as I wanted. How can I change the string to become valid JSON?
As Wiktor said your gsub didn't work because you are attempting to replace backslashes, but there aren't any backslashes in your string. R is just using the backslashes as a way to store the double quotes. The third SO post you link does a good job explaining R's string literals which addresses this. A backslash in R is stored as a double backslash.
My first piece of advice would be to use the R package jsonlite to construct your JSON from an R object as opposed to a string if possible (heres the vignette).
Example:
myJSON <- jsonlite::toJSON(list(stim=c("platery","denial","generic")))
# {"stim":["platery","denial","generic"]}
Second, (as the third SO post again does a good job of explaining) copying/pasting the print method of the string may not be the best way to validate the JSON. I'm not sure of the use case, but R storing the double quotes with escape characters is probably not a bad thing.
If you want to get a prettier print method you can use numerous tricks in R (noquote(), cat(), print(quote=F)) but this won't change that R stores the double quotes with backslashes:
Additionally, in some cases constructing the JSON isn't necessary. I have an API built using the plumbr package that returns a list as JSON without any modifications (recJSON <- list(message=messages,recommendations=list(name=names, link=URLs)))

The url in json contains backslashes

I was just wondering why my wcf rest returns json which contains backslahses in the url. it is as below:
https:\/\/s3.amazonaws.com\/reiaustralia\/1fc00dfab25044ecb31e4882121b535e\/jpg\/download.jpg?AWSAccessKeyId=AKIAISTDESL6TBRAVM4Q&Expires=1380692091&Signature=MduuaUAjQRisadtM%2FDuVDemexLY%3D
Thanks
Forward slashes can be escaped with a backslash in JSON, but they don't have to be. So either one of the following:
{"url":"http://www.example.com/"}
or
{"url":"http\/\/www.example.com\/"}
Will parse into an object which has a url property whose string value is http://www.example.com/.
Some technologies will escape out the slashes when generating JSON, and some won't. PHP, for example, has an option called JSON_UNESCAPED_SLASHES which lets you control whether or not to escape your slashes.
You can get see the various escape characters from the json.org home page in the "string" section.
Because // (double slash) in javascript means comment and /{string}/ (string inside slash) is mean regula expression.
So. To keep correct value in json it have to put \ (back slash) in front of / (slash).
They are just escape characters, and when u consume the string in your application it would just be fine

How to escape special characters in building a JSON string?

Here is my string
{
'user': {
'name': 'abc',
'fx': {
'message': {
'color': 'red'
},
'user': {
'color': 'blue'
}
}
},
'timestamp': '2013-10-04T08: 10: 41+0100',
'message': 'I'mABC..',
'nanotime': '19993363098581330'
}
Here the message contains single quotation mark, which is same as the quotation used in JSON. What I do is fill up a string from user inputs such as message. So, I need to escape those kind of special scenarios which breaks the code. But other than string replace, is there any way to make them escape but still allow HTML to process them back to the correct message?
I'm appalled by the presence of highly-upvoted misinformation on such a highly-viewed question about a basic topic.
JSON strings cannot be quoted with single quotes. The various versions of the spec (the original by Douglas Crockford, the ECMA version, and the IETF version) all state that strings must be quoted with double quotes. This is not a theoretical issue, nor a matter of opinion as the accepted answer currently suggests; any JSON parser in the real world will error out if you try to have it parse a single-quoted string.
Crockford's and ECMA's version even display the definition of a string using a pretty picture, which should make the point unambiguously clear:
The pretty picture also lists all of the legitimate escape sequences within a JSON string:
\"
\\
\/
\b
\f
\n
\r
\t
\u followed by four-hex-digits
Note that, contrary to the nonsense in some other answers here, \' is never a valid escape sequence in a JSON string. It doesn't need to be, because JSON strings are always double-quoted.
Finally, you shouldn't normally have to think about escaping characters yourself when programatically generating JSON (though of course you will when manually editing, say, a JSON-based config file). Instead, form the data structure you want to encode using whatever native map, array, string, number, boolean, and null types your language has, and then encode it to JSON with a JSON-encoding function. Such a function is probably built into whatever language you're using, like JavaScript's JSON.stringify, PHP's json_encode, or Python's json.dumps. If you're using a language that doesn't have such functionality built in, you can probably find a JSON parsing and encoding library to use. If you simply use language or library functions to convert things to and from JSON, you'll never even need to know JSON's escaping rules. This is what the misguided question asker here ought to have done.
A JSON string must be double-quoted, according to the specs, so you don't need to escape '.
If you have to use special character in your JSON string, you can escape it using \ character.
See this list of special character used in JSON :
\b Backspace (ascii code 08)
\f Form feed (ascii code 0C)
\n New line
\r Carriage return
\t Tab
\" Double quote
\\ Backslash character
However, even if it is totally contrary to the spec, the author could use \'.
This is bad because :
It IS contrary to the specs
It is no-longer JSON valid string
But it works, as you want it or not.
For new readers, always use a double quotes for your json strings.
Everyone is talking about how to escape ' in a '-quoted string literal. There's a much bigger issue here: single-quoted string literals aren't valid JSON. JSON is based on JavaScript, but it's not the same thing. If you're writing an object literal inside JavaScript code, fine; if you actually need JSON, you need to use ".
With double-quoted strings, you won't need to escape the '. (And if you did want a literal " in the string, you'd use \".)
Most of these answers either does not answer the question or is unnecessarily long in the explanation.
OK so JSON only uses double quotation marks, we get that!
I was trying to use JQuery AJAX to post JSON data to server and then later return that same information.
The best solution to the posted question I found was to use:
var d = {
name: 'whatever',
address: 'whatever',
DOB: '01/01/2001'
}
$.ajax({
type: "POST",
url: 'some/url',
dataType: 'json',
data: JSON.stringify(d),
...
}
This will escape the characters for you.
This was also suggested by Mark Amery, Great answer BTW
Hope this helps someone.
May be i am too late to the party but this will parse/escape single quote (don't want to get into a battle on parse vs escape)..
JSON.parse("\"'\"")
The answer the direct question:
To be safe, replace the required character with \u+4-digit-hex-value
Example:
If you want to escape the apostrophe ' replace with \u0027
D'Amico becomes D\u0027Amico
NICE REFERENCE:
http://es5.github.io/x7.html#x7.8.4
https://mathiasbynens.be/notes/javascript-escapes
Using template literals...
var json = `{"1440167924916":{"id":1440167924916,"type":"text","content":"It's a test!"}}`;
Use encodeURIComponent() to encode the string.
Eg.:
var product_list = encodeURIComponent(JSON.stringify(product_list));
You don't need to decode it since the web server automatically do the same.
To allow single quotes within doubule quoted string for the purpose of json, you double the single quote. {"X": "What's the question"} ==> {"X": "What''s the question"}
https://codereview.stackexchange.com/questions/69266/json-conversion-to-single-quotes
The \' sequence is invalid.
regarding AlexB's post:
\' Apostrophe or single quote
\" Double quote
escaping single quotes is only valid in single quoted json strings
escaping double quotes is only valid in double quoted json strings
example:
'Bart\'s car' -> valid
'Bart says \"Hi\"' -> invalid