How to parse HTML string using JSON.parse() in JavaScript? - javascript

I have an ASP.NET MVC application returning a JSON string to the VIEW.
// Parsing the model returned on the VIEW
var jsonString = '#Html.Raw(Model.ToJson())';
var jsonObj = JSON.parse(jsonString);
The problem is that I am not able to parse because the jsonString contains characters such as "\" and "'".
//Sample string
{ "description" : "<p>Sample<span style=\"color: #ff6600;\"> Text</span></strong></p>" }

JSON is valid JavaScript, so you can just do this:
var jsonObj = #Html.Raw(Model.ToJson());
FYI, the reason the JSON parsing is failing is because the although the " are escaped with \ to make it valid JSON, the backslashes themselves need escaping in the string for them to be seen by the JSON parser. Compare:
JSON.parse('"quote: \""'); // error: unexpected string
JSON.parse('"quote: \\""'); // 'quote: "'
This example should also clarify what's happening to the backslashes:
var unescaped = '\"', escaped = '\\"';
console.log(unescaped, unescaped.length); // '"', 1
console.log(escaped, escaped.length); // '\"', 2

If you want to create a valid Javascript string, you need to escape backslashes and apostrophes:
var jsonString = '#Html.Raw(Model.ToJson().Replace("\\", "\\\\").Replace("'", "\\'"))';

There you go:
using Newtonsoft.Json;
JsonConvert.SerializeObject(your html string here);

Related

JSON.parse failing

I'm trying to create a JavaScript object from a JSON string "object" but it fails with the error:
"SyntaxError: JSON.parse: expected ',' or '}' after property value in object at line 1 column 48 of the JSON data"
var jsobj = JSON.parse( '{"lineID":11,"siteID":3,"mystring":"this is a \"Test\" string with quotes"}' );
mystring is a string which includes double quotes but I've escaped them correctly with the backslash. Why would it fail?
I noticed it passes OK on this online JSON parsing site: json parser
The \ character is an escape character for JavaScript and JSON.
When the JavaScript parser parses the string literal it turns \" in the JavaScript source code into " in the string.
When the JSON parser parses the string, it finds an unescaped " and errors.
To include \" in the JSON data, you need to escape the \ in the JavaScript string literal: \\".
var jsobj = JSON.parse('{"lineID":11,"siteID":3,"mystring":"this is a \\"Test\\" string with quotes"}');
console.log(jsobj);
Nesting data formats is always a pain. It is best to avoid doing that whenever possible.
It doesn't make sense to have a string literal containing JSON in JavaScript in the first place.
JSON is a subset of JavaScript. Just use the JSON as a JavaScript literal.
var jsobj = {
"lineID": 11,
"siteID": 3,
"mystring": "this is a \"Test\" string with quotes"
};
console.log(jsobj);
For double quotes you have to use double backslash
var jsobj = JSON.parse( '{"lineID":11,"siteID":3,"mystring":"this is a \\"Test\\" string with quotes"}' );
this should work

how to filter "\" from a json string in javascript

I receive a json string at my node js server which looks like this:
{\"gID\":1,\"sID\":18,\"T\":\"Parking\"}
The reason i put in the "\" is because the string is made in C and the \ is used to escape the " which otherwise ends the string.
The code i use now is:
app.get('/add/:jsonString', function(req, res){
var json = JSON.parse(req.params.jsonString);
});
Is there a way to only delete the \'s in my string?
Why do you want to remove it, it's not necessary ?
var a ="{\"gID\":1,\"sID\":18,\"T\":\"Parking\"}";
console.log(JSON.parse(a));
// give Object { gID: 1, sID: 18, T: "Parking" }
EDIT
Use Url encode to pass your get json
var str = encodeURIComponent("{\"gID\":1,\"sID\":18,\"T\":\"Parking\"}");
// send your request
request.get({uri:"website/api?data="+str}, ...
And in server, decode uri then parse
var string = decodeURIComponent(req.query.data);
var obj = JSON.parse(string);
If you want to remove the "\", try the replace method with a regex pattern:
str.replace(/\\/g, "")
The g flag is used to replace all occurences of the char "\", while the first "\" is an escape character.
For further details, consult MDN
I would suggest that you pass JSON into your application using a POST request, as there are plenty of characters that aren't URI-safe.
However, you can use the unescape method from the built in querystring module.
const qs = require('querystring');
app.get('/add/:jsonString', function(req, res){
const json = JSON.parse(qs.unescape(req.params.jsonString));
});

JavaScript json.parse string error

I want to parse this string to an array
var string= "['one','two']";
var result= JSON.parse(string);
It throws an error
`Unexpected token ' in JSON at position 1'
I believe my approach is right I just can't figure out why its throwing that error.
You should use double quotes:
var string = '["one", "two"]';
You can't use single quote in a JSON string.
Just make it like this
var string= '["one","two"]';
var result= JSON.parse(string);
Json standard requires that the string have double quotes inside.

How do JSON.parse() and escape characters work in JavaScript?

Suppose I have an object variable:
var obj = {
key: '\"Hello World\"'
}
Then I tried parse it to string by using JSON.stringify in Chrome devtools console:
JSON.stringify(obj) // "{"key":"\"Hello World\""}"
I get the result "{"key":"\"Hello World\""}". Then I give it to a string
var str = '{"key":"\"Hello World\""}'
At least I try to convert it back to obj:
JSON.parse(str);
but the browser tell me wrong Uncaught SyntaxError
What confused me is why this is wrong? I get the string from an origin object and I just want turn it back.
How can I fix this problem? If I want do the job like convert obj to string and return it back, how can I do?
You're tried to convert your JSON into a string literal by wrapping it in ' characters, but \ characters have special meaning inside JavaScript string literals and \" gets converted to " by the JavaScript parser before it reaches the JSON parser.
You need to escape the \ characters too.
var str = '{"key":"\\"Hello World\\""}'
That said, in general, it is better to not try to embed JSON in JavaScript string literals only to parse them with JSON.parse in the first place. JSON syntax is a subset of JavaScript so you can use it directly.
var result = {"key":"\"Hello World\""};
try:
var str = '{"key":"\\"Hello World\\""}';

Javascript string parser - escape issue

I'm running a Node server that receives a plain utf8 text and parses the content to JSON. Part of the JSON will be the body of an HTML document.
The problem is that when the input has characters such as "รค" or " ' ", the HTML document gets all crazy. I guess it has to do with the coding/decoding of the parser for these special characters.
Any ideas regarding this ?
[EDIT]
The parsing and JSON object are basically this:
var string = <mail_body><html> html code here...<html><mail_body>
var mail_body = string.split("<mail_body>")[1]
var obj = {
"subject": "subject 123",
"mail_body": mail_body
}
You can use this for the "'"
var escapedText = text.replace(/\\'/g, "\\'");
and use a unicode for the "letter a with eyes"
like this -> \u2665
https://mathiasbynens.be/notes/javascript-escapes
The most important thing you need to do is to escape the incoming string to eliminate quotes that will break your JSON, which is the only significant problem I would expect to see with Node - browsers have a slightly harder time. From your input you're looking at something like this:
var string = <mail_body><html> html code here...<html><mail_body>
var mail_body = string.split("<mail_body>")[1]
mail_body = mail_body.replace(/\"/g, '\\"'); // regex for global replace, have to escape quotes
That should get you a mail body that doesn't unexpectedly end and break the rest of your JSON.

Categories

Resources