Why does JS String differ from JSON String? - javascript

I'm using this lib to display emojis.
I want to get my data from a JSON, but for some reason the lib cannot convert a string from JSON.
When I create my own string with the same data, e.g. '\uD83D\uDE18' it displays without any problem.
emojis.posts[0].content == '\uD83D\uDE18' returned false
So my question is, what is the difference between a 'normal' string and a JSON string?
JSON
{
   "title": "l\\u2764 you\\uD83D\\uDE18"
}
...
var emojis = JSON.parse(jsonString);
console.log(emojis.title);
returns 'l\u2764 you\uD83D\uDE18'
Creating a JSON in JS
var emojis = JSON.parse('{"title": "l\\u2764 you\\uD83D\\uDE18"}');
console.log(emojis.title);
returns 'l❤ you😘'
Found the answer: https://stackoverflow.com/a/7885499/6216557
This is a unicode, escaped string. First the string was escaped, then
encoded with unicode

Related

Serialize for JavaScript apex

I need to serialize some simple object from .NET to JavaScript...
But I've some problem with apex...
C# example
var obj = new { id = 0, label = #"some ""important"" text" };
string json1 = Newtonsoft.Json.JsonConvert.SerializeObject(obj);
string json2 = Newtonsoft.Json.JsonConvert.SerializeObject(obj,
new Newtonsoft.Json.JsonSerializerSettings()
{
StringEscapeHandling = Newtonsoft.Json.StringEscapeHandling.EscapeHtml
});
JavaScript example
var resJson1= JSON.parse('{"id":0,"label":"some \"important\" text"}');
var resJson2= JSON.parse('{"id":0,"label":"some \u0022important\u0022 text"}');
Both parse give me the same error
VM517:1 Uncaught SyntaxError: Unexpected token I in JSON at position
23 at JSON.parse(<anonymous>)
Where am I wrong?
You're pasting the generated string of JSON into a JavaScript string constant without escaping it further. Try
console.log('{"id":0,"label":"some \"important\" text"}');
You'll see {"id":0,"label":"some "important" text"} i.e. the "important" quotes are no longer escaped by backslashes. (And you'll get the same for your \u0022 example too.) If you want to paste in the backslashes you'll have to escape them again:
var resJson1= JSON.parse('{"id":0,"label":"some \\"important\\" text"}');
The JSON you've generated with a single backslash would be fine if read from a file or URL, just not pasted into JavaScript as a string constant.

Javascript convert windows-1252 encoding to UTF-8

How do I convert the below string:
var string = "Bouchard+P%E8re+et+Fils"
using javascript into UTF-8, so that %E8 would become %C3%A8?
Reason is this character seems to be tripping up decodeURIComponent
You can test it out by dropping the string into http://meyerweb.com/eric/tools/dencoder/ and seeing the console error that says Uncaught URIError: URI malformed
I'm looking specifically for something that can decode an entire html document, that claims to be windows-1252 encoded which is where I assume this %E8 character is coming from, into UTF-8.
Thanks!
First create a map of Windows-1252. You can find references to the encoding using your search engine of choice.
For the sake of this example, I'm going to include on the character in your sample data.
Then find all the percentage signs followed by two hexadecimal characters, convert them to numbers, and convert them using the map (to get raw data), then convert them again using encodeURIComponent (to get the encoded data).
var string = "Bouchard+P%E8re+et+Fils"
var w2512chars = [];
w2512chars[232] = "è"
var percent_encoded = /(%[a-fA-F0-9]{2})/g;
function filter(match, group) {
var number = parseInt(group.substr(1), 16);
var character = w2512chars[number];
return encodeURIComponent(character);
}
string = string.replace(percent_encoded, filter);
alert(string);

How to convert a string value to Json

I receive a string in the format given below (with double quotes around it):
"'{ "param" : "value"}'"
How can I convert this string into json object so that I could use it as
alert(obj.param)
Thank you
Edit
As I mentioned in above the string has double quotes around it. Here is an example of how I get this string
CSHTML
#{
var prop = "{ \"param\" : \"value\"}";
<a data-type="#prop"></a>
}
and in JS I have this
var obj = anchor.data('type');
I want to be able to use obj.param, how do I achieve this?
Thanks
Use JSON.parse it parses a string as a JSON
var obj = JSON.parse(json);

convert invalid JSON string to JSON

I have an invalid json string like following,
"{one: 'one', two: 'two'}"
I tried to use JSON.parse to convert it to an object. however, this is not valid json string.
Is there any functions can convert this invalid format into a valid json string or directly convert into an object?
IF your example syntax is the same as your real JSON, JSONLint says you need double quote for the name AND the value.
In this case only, use these replace calls:
var jsontemp = yourjson.replace((/([\w]+)(:)/g), "\"$1\"$2");
var correctjson = jsontemp.replace((/'/g), "\"");
//yourjson = "{one: 'one', two: 'two'}"
//jsontemp = "{"one": 'one', "two": 'two'}"
//correctjson = "{"one": "one", "two": "two"}"
However you should try to work with a valid Json in the first place.
If the question is "can I convert invalid JSON into valid JSON", in the general case the answer is obviously "no"; where would you even start with a string like "$#!~~"?
In this particular case, the JSON is only invalid because the property names are not quoted; as JavaScript, the string is valid and could be parsed using, for example,
var myObj = eval( "x=" + myString );
or better
var myObj = (new Function("return " + myString))();
However, this is potentially very unsafe and you should not do it unless you are positive the string cannot cause harm (which seems unlikely if you aren't in a position to generate valid JSON in the first place). It also won't help you if the JSON code is invalid in other ways, and it will fail if the property names are not valid JS identifiers.
For a proper answer it would be useful to know more about the context of this question.

JSON.stringify escaping without need

JSON.stringify is converting my json object to the following string
{\"2003\":{\"1\":{\"2\":[\"test\"],\"3\":[\"test2\"]}}}
When it should not be escaped. The result should be as the string quoted below
{"2003":{"1":{"2":["test"],"3":["test2"]}}}
Rather than use a general replace of all the escaped quotes and remove ones that could be in the input. How can I set JSON.stringify to not double escape the variables?
You are stringifying a string, not an object:
var str = '{"2003":{"1":{"2":["test"],"3":["test2"]}}}';
var obj = {"2003":{"1":{"2":["test"],"3":["test2"]}}};
console.log( JSON.stringify(str) ); // {\"2003\":{\"1\":{\"2\":[\"test\"],\"3\":[\"test2\"]}}}
console.log( JSON.stringify(obj) ); // {"2003":{"1":{"2":["test"],"3":["test2"]}}}
Try these two examples in browser`s console:
let obj = {2003:{1:{2:["test"],3:["test2"]}}};
JSON.stringify(obj);
-> "{\"2003\":{\"1\":{\"2\":[\"test\"],\"3\":[\"test2\"]}}}"
and
let obj = {2003:{1:{2:["test"],3:["test2"]}}};
console.log(JSON.stringify(obj));
-> {"2003":{"1":{"2":["test"],"3":["test2"]}}}
In both cases the string returned from JSON.stringify is valid
In the first case you print "raw" string to console which starts and ends with double quote and all nested double quotes need to be escaped (\" instead of "). JSON validators will mark this string as malformed JSON but it is still parsable with JSON.parse
In the second case you print string "interpreted" as JSON by console.log. JSON validators will mark it as valid JSON but it is no parsable with JSON.parse because it is not string (no quotes around)

Categories