JSON get parsed in browser but not by node.js - json

i'm about to write some test for my client UI.
the weird thing, my JSON string:
{"match":"\s?5\.7\s?\<=\>\s?7","success":"null-coalesce-operator"}
used to be parsed by JSON.parse by browser(Chrome) and looks like this:
{
match: "\s?5\.7\s?\<=\>\s?7",
success:"null-coalesce-operator"
}
everything is fine,
but when i run that part by mocha within node.js env, i get:
{"match":"\s?5\.7\s?\<=\>\s?7","success":"null-coalesce-operator"}
^
SyntaxError: Unexpected token s
at Object.parse (native)
...
did anyone experienced stuff like this. thx for any tipp.
node version is v5.7.1
mocha version is 2.4.5
UPDATE html string that i test is:
<!doctype html><html><body><div data-meta="{"match":"\\s?5\\.7\\s?\\<=\\>\\s?7","success":"null-coalesce-operator"}"></div></body></html>
it just a single line string without any \n newlines and the same.

I think it is because it also parse specials characaters (e.g \n => line feed, \r => carriage return, etc), what chrome did not. So because you want an antislash in you regex, before parsing in node, you need to replace each\ by \\:
json_string = json_string.replace(new RegExp('\\\\', 'g'), '\\\\') //we have to use regex, because when using replace with string, it only replaces the first occurence...
otherwise, when parsing, it will tell, à \s : 'It is a special character, identified by s. But I haven't any tokens s. So I throw an error."

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.

How to insert multi line string into coffeescript/jquery value with Rails

I have some CoffeeScript in my Rails project, with which I'm trying to update a textarea. My CoffeeScript is:
$('#video_description').val(<%= #description %>")
The returned text is a string from the YT gem (a description from one of my YouTube videos). An example can be:
Testing that this works
Does this work?
When I load the page and inspect it with the Developer Tools in Chrome, the CoffeeScript looks like:
$('#video_description').val("Testing that this works
Does this work?")
The new line avoids the CoffeeScript from making sense to the interpreter, and it raises the following message:
Uncaught SyntaxError: Invalid or unexpected token
I've tried replacing the CoffeeScript with:
$('#video_description').val(<%= h #description %>")
This has no effect (other than to escape all the single quotes in the actual string). It has something to do with the fact the string is dropped into the quotes as is.
I need to have the text string to have \n instead of the carriage return.
Any help to solve this would be great.
Use the escape_javascript() method (shortcut: j())
$('#video_description').val("<%= j(#description) %>");

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.

invalid character in json response

in my cakephp controller i send the json response with
$response = array('success' => 1);
return json_encode($response);
i am alway getting a wrong json in my view: SyntaxError: JSON.parse: unexpected character
i have tested with JSLint, the error is "unsafe Character" char 0 line 1
firebug console output returns 65279 for the following statement.
console.log(response.charCodeAt(0));
what can i do? is this an UTF-8 issue?
You may have the character  in your json string which is the Unicode Character ZERO WIDTH NO-BREAK SPACE (U+FEFF). It may be that you copied it into your code via a copy/paste without realizing it. It is not visible so it is hard to debug. Try copy the $response text into a text editor and erase the space.
Here is a post that may be related.
https://stackoverflow.com/a/9691839/2777098

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