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
Related
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
In my app a user submits text through a form's textarea and this text is passed on to the app and is then processed by jsesc library, which escapes javascript strings.
The problem is that when I type in a text in Russian, such as
нам #интересны наши #идеи
what i get is
'\u043D\u0430\u043C #\u0438\u043D\u0442\u0435\u0440\u0435\u0441\u043D\u044B \u043D\u0430\u0448\u0438 #\u0438\u0434\u0435\u0438'
I then need to pass this data through FlowDock to extract hashtags and FlockDock just does not recognize it.
Can someone please tell me
1) What is the need for converting it into that representation;
2) If it makes sense to convert it back to cyrillic encoding for FlowDock and for the database, or shall I keep it in Unicode and try to make FlowDock work with it?
Thanks!
UPDATE
The complete script is:
result = getField(req, field);
result = S(result).trim().collapseWhitespace().s;
// at this point result = "нам #интересны наши #идеи"
result = jsesc(result, {
'quotes': 'double'
});
// now i end up with Unicode as above above (\u....)
var hashtags = FlowdockText.extractHashtags(result);
FlowDock receives the result which is
\u043D\u0430\u043C #\u0438\u043D\u0442\u0435\u0440\u0435\u0441\u043D\u044B \u043D\u0430\u0448\u0438 #\u0438\u0434\u0435\u0438
And doesn't extract hashtags from it...
These are 2 representations of the same string:
'нам #интересны наши #идеи' === '\u043D\u0430\u043C #\u0438\u043D\u0442\u0435\u0440\u0435\u0441\u043D\u044B \u043D\u0430\u0448\u0438 #\u0438\u0434\u0435\u0438'
looks like flowdock-text doesn't work well with non-ASCII characters
UPD: Tried, actually works well:
fdt.extractHashtags('\u043D\u0430\u043C #\u0438\u043D\u0442\u0435\u0440\u0435\u0441\u043D\u044B \u043D\u0430\u0448\u0438 #\u0438\u0434\u0435\u0438');
You shouldn't have used escaping in the first place, it gives you string literal representation (suits for eval, etc), not a string.
UPD2: I've reduced you code to the following:
var jsesc = require('jsesc');
var fdt = require('flowdock-text');
var result = 'нам #интересны наши #идеи';
result = jsesc(result, {
'quotes': 'double'
});
var hashtags = fdt.extractHashtags(result);
console.log(hashtags);
As I said, the problem is with jsesc: you don't need it. It returns javascript-encoded string. You need when you are doing eval with concatenation to protect from code injection, or something like this. For example if you add result = eval('"' + result + '"');, it will work.
What is the need for converting it into that representation?
jsesc is a JavaScript library for escaping JavaScript strings while generating the shortest possible valid ASCII-only output. Here’s an online demo.
This can be used to avoid mojibake and other encoding issues, or even to avoid errors when passing JSON-formatted data (which may contain U+2028 LINE SEPARATOR, U+2029 PARAGRAPH SEPARATOR, or lone surrogates) to a JavaScript parser or an UTF-8 encoder, respectively.
Sounds like in this case you don’t intend to use jsesc at all.
Try this:
decodeURIComponent("\u043D\u0430\u043C #\u0438\u043D\u0442\u0435\u0440\u0435\u0441\u043D\u044B \u043D\u0430\u0448\u0438 #\u0438\u0434\u0435\u0438");
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);
}
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
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)