php json_encode different output than js JSON.stringify [duplicate] - javascript

This question already has an answer here:
Reference: Why are my "special" Unicode characters encoded weird using json_encode?
(1 answer)
Closed 3 years ago.
I get two different results for
json_encode([ 'name' => 'xxx❤xxx' ]);
--> {"name":"xxx\u2764xxx"}
JSON.stringify({ name: 'xxx❤xxx');
--> {"name":"xxx❤xxx"}
Why is that and how can I make sure that the js version produces the same result as the php version?

The escaping in PHP is optional but not technically required for valid JSON (which can contain arbitrary Unicode aside from a few reserved whitespace characters). The feature can be turned off with json_encode($data, JSON_UNESCAPED_UNICODE).
Unfortunately, the JS version doesn't have the feature at all. If you want to escape multibyte characters to \u...., you should do it explicitly; see JSON.stringify and unicode characters.

Related

How can I cleanse a String to contain only digits (0-9) and the letter X (uppercase) only, using Java and Javascript [duplicate]

This question already has answers here:
Remove non-numeric characters except points, commas and '$'?
(2 answers)
Closed 2 years ago.
I am taking an ISBN input by the user - may contain spaces and hyphens etc. - and trying to sanitise it to be only digits.
In Java and Javascript, I have used the following regex successfully
Java (isbn is a java.lang.String)
isbn = isbn.replaceAll("[^\\d]", "");
and, JavaScript
isbn = isbn.replace(/[^\d]/g, "");
However, some ISBNs can have an X as their checksum character. For example, 'The book of days' by Sara Reinke is '155404295X'
How can I change the regex to allow X as well as digits?
Update: [^\dX] worked in JavaScript, but [^\\dX] does not work in Java.
Update 2: PEBKAC! I was sanitising in two places - I updated one but not the other. [^\\dX] does work in Java as well.
Can you try [^0-9X] there? I think it will work in both Java and JavaScript.
P.S. But \\d should work in Java too...
If you wanna follow your solution you can exclude with ?:(values)
For your example it would be: [^\d?:(X)] tested in online java regex.

Symbols inside values breaking if statements in PHP [duplicate]

This question already has answers here:
AJAX POST and Plus Sign ( + ) -- How to Encode?
(6 answers)
Closed 5 years ago.
I have a web app where if someone selects something in the dropdown menu, it changes the next field with Ajax. I'm having difficulty when the values of the dropdown have a '+' symbol which breaks it.
For example this works:
if ($_GET['ch'] == 'Something here - here') {}
However this does not
if ($_GET['ch'] == 'Something here + here') {}
I'd like a solution to be able to include the + symbol inside. Some symbols seem to work fine including brackets (), dashes -, etc.
Try encodeURI function, and/or use POST instead.
Also escaping characters would be good. (like \+ instead of +)
When you are escaping characters than at php side you should use stripslashes function if you need special characters.

Javascript equivalent to Ruby's single quotes? [duplicate]

This question already has answers here:
Does JavaScript have literal strings?
(6 answers)
Closed 7 years ago.
In Ruby, if you use single quotes to make a string, the program parses it so that the output is literally what you wrote.
For example, if you create a string the following way:
variable_a = 'my\nname\nis\nOliver\nQueen'
the output of puts variable_a is
>>my\nname\nis\nOliver\nQueen
However, if you instead use double quotes when building the string, like so:
variable_b = "my\nname\nis\nOliver\nQueen"
the output of puts variable_b would be
>>my
>>name
>>is
>>Oliver
>>Queen
I am looking for a way in Javascript that does just what the single quotes do in Ruby, so that there will be less mistakes when trying to properly build a string that contains backslashes, and other characters that would 'break' the intended string.
Single and double quotes in Javascript are equivalent. The only real reason to use one over the other is preference, and avoiding escaping embedded quotes, e.g.
"Don't need to escape this apostrophe."
or
'No need to escape this "quoted" word.'
Unless you are talking about JSON. In JSON you must use double quotes or it is considered a syntax error by many parsers.

Javascript eval fails on complicated json array [duplicate]

This question already has answers here:
JSON Javascript escape
(4 answers)
Closed 7 years ago.
I want to convert a json string to object by eval, but it fails with error like:
Uncaught SyntaxError: Unexpected identifier VM250:1
below is my string:
'[{"quiz_id":"3","_id":"1","option_in_json":"[{\"option\":\"1\",\"is_answer\":false},{\"option\":\"2\",\"is_answer\":true}]","question":"1+1"}]';
Seems there is something wrong in the bold part, but i don't know how to fix it
The code below is not working
var m='[{"quiz_id":"3","_id":"1","option_in_json":"[{\"option\":\"1\",\"is_answer\":false},{\"option\":\"2\",\"is_answer\":true}]","question":"1+1"}]';
eval(m);
The code below is working so i think the data structure of this json string is ok
var m=[{"quiz_id":"3","_id":"1","option_in_json":"[{\"option\":\"1\",\"is_answer\":false},{\"option\":\"2\",\"is_answer\":true}]","question":"1+1"}];
alert(m[0].option_in_json);
Also tried with $.parseJSON with no luck
It does not work because you are not escaping the data inside the string literal correctly. Look at the value of m in the first case, especially the quotation marks:
[{"option_in_json":"[{"option":"1","is_answer":false}]","question":"1+1"}]
// ^ ^
I removed some irrelevant data. You should be able to see that this cannot be valid JavaScript (or JSON), because the quotation mark before option terminates the string.
In order to put the data inside a string literal, you should either fix the data so that it doesn't contain nested JSON, or escape \:
'[{"option_in_json":"[{\\"option\\": ... }]"}]'
Better of course if you are not putting it in a string literal in the first place.
var m='[{"quiz_id":"3","_id":"1","option_in_json": [{"option":"1","is_answer":false},{"option":"2","is_answer":true}],"question":"1+1"}]';
// ^-- don't wrap in "" so no need to escape inner double quotes.
console.dir(JSON.parse(m));

Encode special characters to pass in url and read by javascript [duplicate]

This question already has answers here:
Encode URL in JavaScript
(22 answers)
Closed 8 years ago.
I need to pass some parameters in the url and they can have special characters like ", spanish Ñ or ñ, : spaces and accents.
What is the propper way to encode them before adding to the url or in case I got in the html like that, read them?
I tried this:
arrayData[i] = pair[1].replace('+', " ").replace('%22', "\"");
But just get working with + or spaces, not both at the same time or in 2 lines:
arrayData[i] = pair[1].replace('+', " ");
arrayData[i] = pair[i].replace('%22', "\"");
You can try encodeUri Built-in function, for example
encodeURI('coño funcionó!')
Previous answer is correct. JavaScript has built in functions for fulfilling this kind of tasks.
You can try to investigate these functions in w3schools.com. Here are the links with basic information and live "Try it out" feature:
encodeURI - takes string with your characters and encodes it into plausible for url style ( encoding spaces and non ANSII chars )
decodeURI - takes encoded string and decodes it to initial state

Categories

Resources