json parse - unescaping the quotes - javascript

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)

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

Error Parsing JSON with escaped quotes

I am getting the following json object when I call the URL from Browser which I expect no data in it.
"{\"data\":[], \"SkipToken\":\"\", \"top\":\"\"}"
However, when I tried to call it in javascript it gives me error Parsing Json message
dspservice.callService(URL, "GET", "", function (data) {
var dataList = JSON.parse(data);
)};
This code was working before I have no idea why all of a sudden stopped working and throwing me error.
You say the server is returning the JSON (omitting the enclosing quotes):
{\"data\":[], \"SkipToken\":\"\", \"top\":\"\"}
This is invalid JSON. The quote marks in JSON surrounding strings and property names should not be preceded by a backslash. The backslash in JSON is strictly for inserting double quote marks inside a string. (It can also be used to escape other characters inside strings, but that is not relevant here.)
Correct JSON would be:
{"data":[], "SkipToken":"", "top":""}
If your server returned this, it would parse correctly.
The confusion here, and the reports by other posters that it seems like your string should work, lies in the fact that in a simple-minded test, where I type this string into the console:
var x = "{\"data\":[], \"SkipToken\":\"\", \"top\":\"\"}";
the JavaScript string literal escaping mechanism, which is entirely distinct from the use of escapes in JSON, results in a string with the value
{"data":[], "SkipToken":"", "top":""}
which of course JSON.parse can handle just fine. But Javascript string escaping applies to string literals in source code, not to things coming down from the server.
To fix the server's incorrectly-escaped JSON, you have two possibilities. One is to tell the server guys they don't need to (and must not) put backslashes before quote marks (except for quote marks inside strings). Then everything will work.
The other approach is to undo the escaping yourself before handing it off to JSON.parse. A first cut at this would be a simple regexp such as
data.replace(/\\"/g, '"')
as in
var dataList = JSON.parse(data.replace(/\\"/g, '"')
It might need additional tweaking depending on how the server guys are escaping quotes inside strings; are they sending \"\\"\", or possibly \"\\\"\"?
I cannot explain why this code that was working suddenly stopped working. My best guess is a change on the server side that started escaping the double quotes.
Since there is nothing wrong with the JSON string you gave us, the only other explanation is that the data being passed to your function is something other than what you listed.
To test this hypothesis, run the following code:
dspservice.callService(URL, "GET", "", handler(data));
function handler(data) {
var goodData = "{\"data\":[], \"SkipToken\":\"\", \"top\":\"\"}";
alert(goodData); // display the correct JSON string
var goodDataList = JSON.parse(goodData); // parse good string (should work)
alert(data); // display string in question
var dataList = JSON.parse(data); // try to parse it (should fail)
}
If the goodData JSON string can be parsed with no issues, and data appears to be incorrectly-formatted, then you have the answer to your question.
Place a breakpoint on the first line of the handler function, where goodData is defined. Then step through the code. From what you told me in your comments, it is still crashing during a JSON parse, but I'm willing to wager that it is failing on the second parse and not the first.
Did you mean that your JSON is like this?
"{\"data\":[], \"SkipToken\":\"\", \"top\":\"\"}"
Then data in your callback would be like this:
'"{\"data\":[], \"SkipToken\":\"\", \"top\":\"\"}"'
Because data is the fetched text content string.
You don't have to add extra quotes in your JSON:
{"data":[], "SkipToken":"", "top":""}

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

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);
}

Parsing JSON with special characters

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

Categories

Resources