Parse error creating Erlang JSON string - json

I'm having trouble properly escaping a string I'm trying to use to represent JSON in Erlang. I'm not sure why this particular sequence is giving the parser trouble. I have this string in a Basho Bench configuration file.
'{
"stats":"completed",
"times":[
{
"time":"2014-10-29T23:40:46.558Z"
}
]
}'
I am getting this error:
23:37:18.521 [error] Failed to parse config file server/http.config.erl: {29,erl_scan,{illegal,atom}}
It seems like maybe the issue is the numbers in the string but I don't get how I would escape them. Any thoughts?

You provided insufficient info but anyway, server/http.config.erl is not JSON. It is erlang term, so this error is from Erlang parser. The whole text you provided is parsed as atom because of ' which is delimiter for atoms.

The string is not a string. Single quotes denote an atom. It must be wrapped in double quotes to be interpreted as a string.

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.

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)))

Strip backslashes from encoded JSON response

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)).

How does parsing special characters in JSON work?

Alright, I know i’m probably going to get yelled at for asking such a ‘simple’ question (seems to be the trend around here) but check it out…
I am building a JSON parser and got everything working correctly except the parsers ability to deal with special characters. I am trying to implement the same special characters that are listed on http://www.json.org/ namely, [", \, /, b, f, n, r, t, u].
When I run these special characters through the builtin JSON.parse method though, most of them either return an error or don’t do anything at all
JSON.parse('["\\"]')
SyntaxError: Unexpected end of input
JSON.parse("['\"']")
SyntaxError: Unexpected token ‘
JSON.parse('["\b"]')
SyntaxError: Unexpected token
JSON.parse('["\f"]')
SyntaxError: Unexpected token
Yes, I see the other post "Parsing JSON with special characters", it has nothing to do with my question. Don't refer me to another question, I have seen them all. How does parsing special characters in JSON work?
JSON.parse expects JavaScript strings.
JavaScript string literals use backslashes for escaping.
JSON uses backslashes for escaping.
So...
JSON.parse('["\\\\"]')
// ["\"]
JSON.parse("['\"']")
// SyntaxError: Unexpected token '
// JSON doesn't have single quotes as string delimiters!
JSON.parse('["\\b"]')
// [""]
JSON.parse('["\\f"]')
// [""]
JSON.parse('["\\\\b"]')
// ["\b"]
JSON.parse('["\\\\f"]')
// ["\f"]
The reason you've got an issue here is because \ is also a marker for special characters within javascript strings.
Take your first example: '["\\"]'. As javascript parses this string, \\ is escaped to a single \ in your string, so the value passed to JSON.parse method is actually ["\"] - hence the "unexpected end of input error".
Essentially, you need to cater for the javascript parser by doubling-up on the backslash escape sequences. In this case, to pass your intended ["\\"] value to JSON.parse, you need to use JSON.parse('["\\\\"]') in javascript as that will pass the string ["\\"] into the JSON.parse method.

Why does JSON.parse choke on encoded characters in nodejs?

I'm attempting to look up the word "flower" in Google's dictionary semi-api. Source:
https://gist.github.com/DelvarWorld/0a83a42abbc1297a6687
Long story short, I'm calling JSONP with a callback paramater then regexing it out.
But it hits this snag:
undefined:1
ple","terms":[{"type":"text","text":"I stopped to buy Bridget some \x3cem\x3ef
^
SyntaxError: Unexpected token x
at Object.parse (native)
Google is serving me escaped HTML characters, which is fine, but JSON.parse cannot handle them?? What's weirding me out is this works just fine:
$ node
> JSON.parse( '{"a":"\x3cem"}' )
{ a: '<em' }
I don't get why my thingle is crashing
Edit These are all nice informational repsonses, but none of them help me get rid of the stacktrace.
\xHH is not part of JSON, but is part of JavaScript. It is equivalent to \u00HH. Since the built-in JSON doesn't seem to support it and I doubt you'd want to go through the trouble of modifying a non-built-in JSON implementation, you might just want to run the code in a sandbox and collect the resulting object.
According to http://json.org, a string character in a JSON representation of string may be:
any-Unicode-character-
except-"-or--or-
control-character
\"
\
\/
\b
\f
\n
\r
\t
\u four-hex-digits
So according to that list, the "json" you are getting is malformed at \x3
The reason why it works is because these two are equivalent.
JSON.parse( '{"a":"\x3cem"}' )
and
JSON.parse( '{"a":"<em"}' )
you string is passed to JSON.parse already decoded since its a literal \x3cem is actually <em
Now, \xxx is valid in JavaScript but not in JSON, according to http://json.org/ the only characters you can have after a \ are "\/bfnrtu.
answer is correct, but needs couple of modifications. you might wanna try this one: https://gist.github.com/Selmanh/6973863