I have div content and div contains text like javascript Object.
<div class="data-content">{ title: "Yes", value : 4247, color: "#FC4349", total_votes: "10968", percentage: "39%"}, { title: "No", value : 6721, color: "#2980b9", total_votes: "10968", percentage: "61%"}</div>
<script> var data = $('.data-content').text();</script>
currently data value is as a string and I want it as object not string.
Is it possible or any other way to get div content as javascript object?
any help is appreciated.
Just try with:
var data = $('.data-content').text();
var output = JSON.parse('[' + data.replace(/\b([a-z_]+)\b/g, '"$1"') + ']');
What happens here ? Valid JSON format requires keys to be wrapped with apostrophes, so we wrap them with /\b([a-z_]+)\b/g regex.
After that we get only objects separated with comma, so we have to wrap it with [] to make an array. Since now it's valid for JSON parser and we get expected result.
http://jsfiddle.net/8ubFY/
Use JSON.parse() as in:
var transformed = JSON.parse(data);
The linked documentation gives details on how to add error handling if your JSON text is invalid. You can also use jQuery.parseJSON() for better browser support as in:
var transformed = jQuery.parseJSON(data);
Okay, so your JSON was also invalid, see JSON object for documentation of valid JSON objects. I have fixed it up and created a JSFiddle to show the correct code.
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 am trying to fetch numeric value from link like this.
Example link
/produkt/114664/bergans-of-norway-airojohka-jakke-herre
So I need to fetch 114664.
I have used following jquery code
jQuery(document).ready(function($) {
var outputv = $('.-thumbnail a').map(function() {
return this.href.replace(/[^\d]/g, '');
}).get();
console.log( outputv );
});
https://jsfiddle.net/a2qL5oyp/1/
The issue I am facing is that in some cases I have urls like this
/produkt/114664/bergans-of-norway-3airojohka-3jakke-herre
Here I have "3" inside text string, so in my code I am actually getting the output as "11466433" But I only need 114664
So is there any possibility i can get numeric values only after /produkt/ ?
If you know that the path structure of your link will always be like in your question, it's safe to do this:
var path = '/produkt/114664/bergans-of-norway-airojohka-jakke-herre';
var id = path.split('/')[2];
This splits the string up by '/' into an array, where you can easily reference your desired value from there.
If you want the numerical part after /produkt/ (without limitiation where that might be...) use a regular expression, match against the string:
var str = '/produkt/114664/bergans-of-norway-3airojohka-3jakke-herre';
alert(str.match(/\/produkt\/(\d+)/)[1])
(Note: In the real code you need to make sure .match() returned a valid array before accessing [1])
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 want to put a JSON object into a javascript variable as a sting in order to create a graph.
qm.createGraphData = function() {
$.post("ajax_getGraphDataWebsite ", function(json) {
qm.negativesData = json;
},"json");
qm.data = [{
"xScale":"ordinal",
"comp":[],
"main":[{
"className":".main.l1",
qm.negativesData},{
"className":".main.l2",
qm.negativesData}],
"type":"line-dotted",
"yScale":"linear"}];
}
the string value should be added to the "data" section. Now the object get's added but I need to add the string value to the variable like the sample below:
{"data":[{"x":"3283581","y":"2013-10-16"},{"x":"1512116","y":"2013-10-17"},{"x":"3967","y":"2013-10-18"},{"x":"1094","y":"2013-10-19"},{"x":"853","y":"2013-10-20"},{"x":"1205","y":"2013-10-21"},{"x":"2618700","y":"2013-10-22"},{"x":"3928291","y":"2013-10-23"},{"x":"3670318","y":"2013-10-24"},{"x":"3347369","y":"2013-10-25"},{"x":"2525573","y":"2013-10-26"},{"x":"3224612","y":"2013-10-27"},{"x":"3992964","y":"2013-10-28"},{"x":"3949904","y":"2013-10-29"},{"x":"3568618","y":"2013-10-30"},{"x":"3104696","y":"2013-10-31"},{"x":"3246932","y":"2013-11-01"},{"x":"2817758","y":"2013-11-02"},{"x":"3198856","y":"2013-11-03"},{"x":"3952957","y":"2013-11-04"},{"x":"3934173","y":"2013-11-05"},{"x":"3878718","y":"2013-11-06"},{"x":"3642822","y":"2013-11-07"},{"x":"3186096","y":"2013-11-08"}]}
This would generate the right graph for me. Does anyone know how to convert the json object into a string like above and to send it to the qm.negativesData variable?
// UPDATE
Now I've got the string with the qm.negativesData = JSON.stringify(json); solution
But my qm.negativesdata won't get added to the qm.data variable... i'm getting a console error SyntaxError: invalid property id
I suppose i'm not adding them the right way?
To convert a JSON object into a JSON string, you can try myObject.stringify(), JSON.stringify(myObject), or if you are using a library using the built in function of that library.
So, you could do something like: qm.negativesData = myObject.stringify()
Cheers
I am encoding some model data into a html element like this:
#Html.Raw(Json.Encode(Model));
The json string returned looks like this:
{"TestList":[{"FrequencyType":"1X","GCDs":"585.6","Identifier":"6144","SeqNo":9306,"SeqNoSpecified":true,"TSeqNo":8314,"TSeqNoSpecified":true,"TestDescr":"HBsAg"},{"FrequencyType":"1X","GCDs":"585.6","Identifier":"6124","SeqNo":9295,"SeqNoSpecified":true,"TSeqNo":8315,"TSeqNoSpecified":true,"TestDescr":"HCV Ab"},{"FrequencyType":"1X","GCDs":"585.3","Identifier":"6","SeqNo":9729,"SeqNoSpecified":true,"TSeqNo":8309,"TSeqNoSpecified":true,"TestDescr":"HD Monthly LS"}],"Frequency":[{"Key":"ANNUAL","Value":"Annually"},{"Key":"BIMONTH","Value":"Bi-Monthly"},{"Key":"BIWEEK","Value":"Bi-Weekly"},{"Key":"MON","Value":"Monthly"},{"Key":"1X","Value":"One Time"},{"Key":"QTR","Value":"Quarterly"},{"Key":"SMAN","Value":"Semi-Annual"},{"Key":"WEEK","Value":"Weekly"}]};
When I try to parse this using JSON.parse, I get an error:
arrayTestList = [];
var jsonTestList = $('#TestList').text();
jsonTestList = JSON.stringify(jsonTestList);
arrayTestList = JSON.parse(jsonTestList);
alert(arrayTestList.TestList[0]); // <===== this line is failing
Unable to get value of the property '0': object is null or undefined
How do I convert this jsonTestList string into a javascript array so that I can access elements of arrayTestList properly?
Edit:
Sorry, I forgot to mention my edit. Basically above javascript code is inside a Partial View 2. The code where I am json encoding the model is in another Partial View 1. From P V 2, I cannot access the model object of P V 1, so I am just dumping the contents into a div tag, so that I can access this list TestList element.
Try removing this line:
jsonTestList = JSON.stringify(jsonTestList);
jsonTestList is already a JSON string
The issue is now resolved.
I was getting an invalid character, but couldn't immediately recognize which character it was that was causing the problem. I found that my JSON string isn't valid because of the trailing semicolon that was output by the Json.Encode method. I validated the JSON string # http://jsonlint.com.
Once I removed that semicolon, the json string is populated as a JavaScript array into arrayTestList object.
Now just this works, as mentioned in both the answers above, JSON.stringify is not needed.
var arrayTestList = [];
var jsonTestList = $('#TestList').text().replace(";","");
arrayTestList = JSON.parse(jsonTestList);
alert(arrayTestList.TestList[0]);
Why are you using Json.Encode? Also in your code, why are you writing redundant code first you are using JSON.stringify and the JSON.parse same object.
jsonTestList = JSON.stringify(jsonTestList);
arrayTestList = JSON.parse(jsonTestList);
As per my understanding just Html.Raw will work
In JavaScript
var jsonObject = #Html.Raw(Model.TestList); //Here you will get JavaScript Object
var jsonTestList = jsonObject.TestList;