I have javascript variable var result as following which has java variable that have JSON data like this
var result = <%=JsonData1%> ;
alert(result.toSource());
Above code similar to this code as showing on alert message
var result= [{"year":"12","value":"6694"},{"year":"13","value":"50"},{"year":"08","value":"4776"},{"year":"09","value":"29006"},{"year":"10","value":"1751"}];
but I need to place a single quote on JSON data
'[{"year":"12","value":"6694"},{"year":"13","value":"50"},{"year":"08","value":"4776"},{"year":"09","value":"29006"},{"year":"10","value":"1751"}]'
and place it in new javascript variable like this
var json_pre = result;
alert(json_pre);
but when I change my result data that placed in new json_pre variable as in this link How to add single quote in the variable in Javascript?
var json_pre = "'" +result+ "'";
alert(json_pre.toSource());
then json data shows me like this on the alert message
'[{year:(new Date(-2208058200000)), value:6694}, {year:(new Date(-2207971800000)), value:50}, {year:(new Date(-2208403800000)), value:4776}, {year:(new Date(-2208317400000)), value:29006}, {year:(new Date(-2208231000000)), value:1751}]'
As I have tried every method that given me on that link.So anyone can help me in this?
result is not JSON, but a JavaScript object.
What you need to do is to stringify your object to JSON and then add the quotes:
var result = [{"year":"12","value":"6694"},{"year":"13","value":"50"},{"year":"08","value":"4776"},{"year":"09","value":"29006"},{"year":"10","value":"1751"}];
var result_pre = "'" + JSON.stringify(result) + "'";
console.log(result_pre);
But it is questionable why you would even need that.
You need to understand the single quotes does not make an object a string. When you are trying to store it in a variable I guess you are making the same mistake again.
when you do this
a={"key":"value"}
b="'" + a + "'";
You get a string representation for consoles, if you want a JSON string to be stored in a variable you need to do this
var json = JSON.stringify(result);
alert(json);
You don't need quotes for that.
Related
i have an issue with my logged Json String as it replaces the double quotes with "
Controller Code :
var message = new SuccessMessagesVM()
{
Title = successMessageType == (int)EnumHelper.SuccessMessageTypes.Add ? "It's beautiful" : CustomModel.Resources.SuccessMessagesResources.EditFormSuccess,
Message = successMessageType == (int)EnumHelper.SuccessMessageTypes.Add ? CustomModel.Resources.SuccessMessagesResources.AddFormSuccess : CustomModel.Resources.SuccessMessagesResources.EditFormSuccess,
ColorCode = (int)EnumHelper.MessagesCodes.Success
};
var json = JsonConvert.SerializeObject(message);
ViewBag.SuccessMessage = successMessageType == 0 ? null : json;
Javascript just logs the ViewBag.SuccessMessage as following:
console.log('#ViewBag.SuccessMessage');
and the object is displayed as {"Message":"تم إضافة النموذج بنجاح","Title":"It's beautiful","ColorCode":3}
replacing all single quotes with ' and all double quotes with "
I expect the output to be {"Message":"تم إضافة النموذج بنجاح","Title":"It's beautiful","ColorCode":3}
This is because you are using ViewBag variable.
In order to use ViewBag, you can write it as followed:
First, in view:
#{
var jss = new System.Web.Script.Serialization.JavaScriptSerializer();
var successMessageJson = jss.Serialize(ViewBag.SuccessMessage);
}
Then use it:
<script>
//use Json.parse to convert string to Json
var successMessageInfo = JSON.parse('#Html.Raw(successMessageJson)');
</script>
There's a few different issues and a few different approaches, and the OP doesn't give us any view code, so it's a bit of guesswork.
My feeling is that you should just return the SuccessMessagesVM from your method, and access the properties individually in your view (probably using #Html.DisplayFor and HTML). This will ensure that any redundant quotation marks are never created in the first place, and will give you total control over how the values are displayed.
You should not expect console.log(#ViewBag.Anything) to display properly. If you need the data as a JavaScript object, don't stick it in the ViewBag, as it will get rendered as HTML.
If you must write to a JavaScript object you can, but it begs the question why are you not using an ajax request if all you want is data?
I'm trying to filter urls I grabbed using json but the code is not working
$.each(data.next, function(z,item){
JSON.stringify(item.data.url);
var url =item.data.url;
if (url.substring(0,11)=='http://youtub'){
var x = '<p>' + url + '</p>'; //this line and the one after that is just to put it in html
$(x).appendTo("#text");
}
});
Where did I make the error? I've never used stringify before so is that it?
Have you try actually using the variable return by JSON.stringify?
var url = JSON.stringify(item.data.url);
JSON.stringify doesn't modify the argument it is given, it return a converted format
See documentation
Also I am not sure why would anyone want to convert an easy to iterate over object into a string to build a filter. If anything a well build object would make filtering a bliss.
I have a string:
a = "{u'a':[u'123',u'321'], u'b':[u'456',u'654']}"
I want to convert this a to a json data.
How to do it?
I have tried JSON.parse(), but it will raise an error.
SyntaxError: Unexpected token u
That looks like Python literal syntax to me. Tell whoever wrote the Python portion to encode as JSON instead of just outputting the structure as a string.
In this particular case, you can just replace each u'x' with "x" and you'll have valid JSON:
var a = "{u'a':[u'123',u'321'], u'b':[u'456',u'654']}";
// Convert to JSON (May not work with other inputs!)
var json = a.replace(/u'((?:[^'\\]|\\.)*)'/g, function(a,str){
return '"' + str.replace(/\\'/g, '\'').replace(/"/g, '\\"') + '"';
});
// Parse the JSON into a Javascript object
var obj = JSON.parse(json);
Updated to work with some quotes in the object:
var a = "{u'a':[u'\\'123\\'',u'321'], u'b':[u'456\\\\',u'\"654\"']}";
Becomes:
{a:["'123'","321"], b:["456\",""654""]}
You need to change your input string to a valid JSON string.
I think this is what you wanted:
JSON.parse('{"a":["123","321"], "b":["456","654"]}')
The variables (keys / values ) are strings so need to be in quotes in order to be parsed as valid JSON.
// put quotes around the key / value pairs.
var a = "{\"u'a'\":[\"u'123'\",\"u'321'\"], \"u'b'\":[\"u'456'\",\"u'654'\"]}";
jQuery
a = $.parseJSON(a);
JSON is supposed to contain only strings.
a = "{u'a':[u'123',u'321'], u'b':[u'456',u'654']}"
Here I can only assume that u is a variable. Change it to this:
a = "{"+u+"'a':["+u+"'123',"+u+"'321'], "+u+"'b':["+u+"'456',"+u+"'654']}"
I am unable to send data through my ajax call if the user put quotes in the textarea. Is there a way to send text with quotes? I dont want to get rid of the quotes. I guess this is usually not a big problem, i found very little online about this situation.
var description = $('#Description').val();
var title = $('#Title').val();
var parameters = '{content:' + $('#ContentCheck').is(':checked') +
',title: "' + title + '",desciption:"' + description + '"}';
Checkout JSON.stringify(object) which is built into javascript.
The jist is, you create a javascript object, and call stringify to create a JSON string. With your information given above, you might do:
var jsonText = JSON.stringify({
'content': $('$('#ContentCheck').is(':checked'),
'title': title,
'description': description
});
Here we define a javascript hash using the curly braces, and then pass it to stringify.
same problem was with me.I tried this and completely working
xmlhttp.open("POST","test_test.php",true);
xmlhttp.setRequestHeader("Content-type","application/x-www-form-urlencoded");
xmlhttp.send("name="+encodeURIComponent(name)+"&details="+encodeURIComponent(details)+"&r_price="+r_price+"&o_price="+o_price+"&id="+id);
and use urldecode($_REQUEST['details'])` when inserting.
You can convert parameters into a map -- basically an associative array -- instead of a string. That way, you can do string manipulation in the backend .NET without any changes in your frontend js; e.g.
var url = 'http://path/to/your/backend/script';
var parameters = {
contentCheck: $('#ContentCheck').is(':checked'),
title: title,
description: description
};
$.post(url, parameters);
You can encode quotes using js and decode it server side to get the original string
//js
function totalEncode(s){
str= s.replace(/\&/g,'&');
str= str.replace(/</g,'<');
str= str.replace(/>/g,'>');
str= str.replace(/\"/g,'"');
str= str.replace(/\'/g,''');
return(str);
}
I'm having trouble printing an object with a variable name. It works when I hard code it.
var objectVarName = "lat";
var obj = jQuery.parseJSON(JSON.stringify(msg));
// {"lat":"93"} is what JSON.stringify(msg) prints
$('#display').prepend("<br/><br/>" + JSON.stringify(msg));
//obj['lat'] works, obj[objectVarName] does not
$('#display').prepend("<br/><br/>" + obj['lat']);
Double check that your variable name, casing, etc are correct...your code works if msg is a valid object, here's what I tested:
var msg = {"lat":"93"};
You can test/see the result here, I changed .prepend() to .append() so the output is in order, no other changes besides that, the result is:
{"lat":"93"}
93