Parsing JSON with special characters - javascript

I am using flot to do some graphing and I am having some trouble passing the tickSize with my json. I am using MVC and pass the json in a model. Here is some code to grab the json within my javascript function:
var json = '<%=Model.Json %>';
var data = jQuery.parseJSON(json);
Here is how the Json looks leaving the controller:
{\"GraphData\":[{\"X\":1333929600000,\"Y\":0.0},{\"X\":1333670400000,\"Y\":0.46}],\"Max\":1333324800000,\"Min\":1333929600000,\"TickSize\":\"[1, 'day']\"}
The part that I am having trouble with is "TickSize." As you can see, "[1, 'day']" has the square brackets. I think there is some parsing problem because [] usually means an array. Flot wants the tick size in this format. How do I construct my Json so I can grab the TickSize?

The issue is the single-quotes in the string value, since you're trying to wrap the JSON string in them as well. The resulting JavaScript will be (truncated):
var json = '...,\"TickSize\":\"[1, 'day']\"}';
Because of the now 4-count of single-quotes, day isn't actually part of the string and creates a syntax error.
But, you shouldn't even need to quote and parse the JSON since it's derived from JavaScript syntax:
var data = <%= Model.Json %>;
If you need the string representation, you can either stringify it in JavaScript:
var json = JSON.stringify(data):
Or escape single-quotes within the string server-side:
var json = '<%= Model.Json.Replace("'", "\\'") %>';

It is because you have surrounded the string with ' instead of ". This is causing the string to terminate with your first '.
Rewrite your first line as
var json = "<%=Model.Json %>";

Solution : replace single backslash '\' with double '\\' back slash.
For Newline character '\n' to '\\n'
Works with Tooltip messages

Related

How to handle JSON string errors (error character ") in javascript

An administrator has directly filled content into the database and formatted it as json string. However, when retrieving it from the database and parse it into json, it failed. Because when filling data directly, instead of content need to write this (\"), they just write (") the json string shield is faulty and cannot parse. How to solve this problem.
Ex:
"aaaa"dddd"aaaa" => "aaaa\"dddd\"aaaa"
I assume that when you retrieve the string from the database, you are getting something like: '"aaaa"dddd"aaaa"'
If so, then you can convert that to a valid JSON string by removing the first and last double quotes and using JSON.stringify to convert the string to a valid JSON string (including escaping the inner double quotes).
For example:
const s = '"aaaa"dddd"aaaa"';
const escaped = JSON.stringify(s.slice(1, -1));
console.log(escaped);
// "aaaa\"dddd\"aaaa"
const parsed = JSON.parse(escaped);
console.log(parsed);
// aaaa"dddd"aaaa
You might use replace with RegExp and g flag
let str = `"aaaa"dddd"aaaa"`;
let result = str.replace(/"/g,`\\"`).slice(1,-2) + '"';
console.log(result)
OP asked My database return result string "aaaa"dddd"aaaa", How to assign such "aaaa"dddd"aaaa"
You can interpolate that return from database into Template Strings
let str = `${database.value}`;
Not sure what database or what language is on server side, however, rather that trying to escape the inner quotes. Trying just replacing the first and last double quote with with a single quote. Not sure of the full context here to know whether this is the issue. Anyway, something to consider

correctly adding to json from javascript

hi im having trouble correctly adding to my json
here is the code.
When i console.log the string im trying to add is
{"type":"#","name":"wh2xogvi","list":[{"0":"background-color"},{"1":"border"},{"2":"width"}, {"3":"height"},{"4":"margin"}],"listvalues":[{"0":"#aaa"},{"1":"2px solid #000"},{"2":"1040px"},{"3":"50px"},{"4":"0 auto"}]}
it is valid json
var jsonltoload = JSON.stringify(eval("(" + jsonloadtostring + ")"));
console.log(jsonltoload); // this is the console log i was talking about higher up
fullJSON.styles.objectcss.push(jsonltoload);
But when i actually look at the json it is wrong ends up something like this
"{\"type\":\"#\",\"name\":\"unkd42t9\",\"list\":[{\"0\":\"background-color\"},{\"1\":\"border\"},{\"2\":\"width\"},{\"3\":\"height\"},{\"4\":\"clear\"}],\"listvalues\":[{\"0\":\"#ddd\"},{\"1\":\"2px solid #000\"},{\"2\":\"100%\"},{\"3\":\"50px\"},{\"4\":\"both\"}]}",
the fullJSON comes from JSON.parse(json); which comes from a file
You seem to confuse JSON, a textual, language-independent data representation, with JavaScript objects, a language-specific data type.
JSON.stringify returns a string (containing JSON), so jsonltoload is a string. I guess you simply want to parse the JSON and add the resulting object:
var obj = JSON.parse(jsonloadtostring);
fullJSON.styles.objectcss.push(obj);
I think the JSON string is trying to escape the double quotes character you have added to string, resulting in the string. try to enclose the whole string with single quotes rather than double quotes

Json parse() does not escape \" in javascript

I have java object which is converted as JSON string using
String paramMap = new ObjectMapper().writeValueAsString(custPolicy.getParamMap());
model.addAttribute("testTypeMap", paramMap );
In the .jsp page, on load I'm trying to parse the testTypeMap and get object back;
var paramMap = JSON.parse('${testTypeMap}');
showTestType('File content', 'LINUX', paramMap);
The object has double quotes (") in one of the fields, and it is escaped with backslash () when it is converted as JSON sting in java, that is why we see "\"" (from view source)
var paramMap = JSON.parse('{"Filepath":"/home/status.txt","Search expression":"\""}');
But the above line says, "Uncaught SyntaxError: Unexpected string".
I have seen few posts and they say it need two parses, one for javascript and one for JSON. I tried to replace \" with \\" ; but in javascript \" is always ", so I could not replace it;
Any pointer for what I miss here?
The problem is that you're not encoding the string in ${testTypeMap} as a JavaScript literal. I'm unsure how to do it specifically in your framework, but it's akin to HTML encoding a string, but for JavaScript instead.
However!
In your specific example you can avoid using JSON.parse because JSON is already in a format consumable by JavaScript.
var paramMap = ${testTypeMap};
showTestType('File content', 'LINUX', paramMap);
With the resulting source sent to browser looking like:
var paramMap = {"Filepath":"/home/status.txt","Search expression":"\""};
Actually I was not knowing how to replace \" with \\" in javascript, as \" is always represented as " (just one quote without backslash).
So I did this replace in server side after converting to a JSON string using Jackson's ObjectMapper as below:
String paramMap = new ObjectMapper().writeValueAsString(custPolicy.getParamMap());
// need to replace any \" with \\" in javascript side
paramMap = paramMap.replace("\\\"", "\\\\\"");
model.addAttribute("testTypeMap", paramMap );
Now in client-side it shows as below:
var paramMap = JSON.parse('{"Filepath":"/home/cavirin/status.txt","Search expression":"\\""}');
and this works fine as javascript parse is already taken care in server side.

Parse json string set by controller, in view

My MVC Controller contains a collection that I want to pass to the view, so I do:
// myCollection is a list of objects
var j = new JavaScriptSerializer();
ViewBag.Data = j.Serialize(myCollection);
And on the view inside JS
var data = $.parseJSON('#Html.Raw(ViewBag.Data)');
.. which expands to look something like:
var data = $.parseJSON('[{"Value":2,"Fullname":"Value"}]');
This works fine, but if my Json string contains a double quote it get's escaped with a backslash, and the parseJson fails, like this:
$.parseJSON('[{"Value":2,"Fullname":"Value \" with double quote"}]');
How do I fix that?
Whilst the following is valid JSON, it doesn't stay like that when the string is in JavaScript as it will unescape first:
'[{"Value":2,"Fullname":"Value \" with double quote"}]'
JavaScript will first unescape this to become:
'[{"Value":2,"Fullname":"Value " with double quote"}]'
When JSON comes along, it obviously sees an unexpected character since the quote is now looking to end the string. What you need to do is double-quote (\\" works) these somehow, whether you want to do it at the JS end or .NET end is probably entirely up to you.
However, there's really no need to parse this using JSON at all and you can just use it as an object literal like so:
var data = #Html.Raw(ViewBag.Data);
which will convert to:
var data = [{"Value":2,"Fullname":"Value \" with double quote"}];
.. which is perfectly valid.
why not just create custom function, and call parseJSON inside of it. but replace \" before that?
function parseJson(str){
var temp = str.replace('\"', '"');
return $.parseJSON(temp);
}

json parse - unescaping the quotes

so i am using json to pass some information from one place to another...
i have:
message.title = 'this is only a "test"';
so obviously, when i use JSON.stringify, i get escaped quotes.
What i want to know is, what is the best way to unescape those quotes when using JSON.Parse.
i have:
var message = JSON.parse(message);
var original = ????;
var final = ????;
var regex = new RegExp(original, 'g');
for(var prop in message){
message.data[prop] = message.data[prop].replace(regex, final);
}
I wish to know if i am doing something wrong and, as i tried various values in 'original' and 'final', what are correct values for them.
Thank you
What i want to know is, what is the best way to unescape those quotes when using JSON.Parse
Do nothing. Parsing JSON will decode escapes. (If that doesn't work, then something is breaking between the data being converted to JSON and being parsed, or the data was bad to begin with)

Categories

Resources