putting json into javascript variable - javascript

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

Related

Javascript: Push Json String to Json object

Im trying to Push a valid json string to javascript json object, but every time im trying to do it like that:
markersData['values'] = [string];
the result is of markersData json object is:
"values":["{'latLng..."
instead of (Original):
"values":[{"latLng...
it take all of the json and push it as one variable (invalid json), how can i push it as a part of the original json?
any idea how to solve it?
Thank you!
You need to deserialise the JSON string before setting it to the property of the object:
markersData['values'] = [JSON.parse(yourJsonString)];
markersData['values'] = [JSON.parse(string)];
Hope this helps.. Read more about JSON.parse here
You need to parse the string first.
JSON.parse(addstringvar);
Code pen demo
var testObj = {};
var addString = '{"name": "test"}';
testObj.values = [JSON.parse(addString)];
You'll need to make sure you have a valid JSON. So below will show you how to create an easy JSON which will be valid for you to use
JSON Object:
var newObject = {};
newObject.Latlng = "ValueHere";
var jsonString = JSON.stringify(newObject);
// Check jsonString before you parse for pushing.
console.log(jsonString);
You will need to deserialise the JSON string before setting it to the
property of the object
like Rory McCrossan mentions in his answer
jsonString[value] = [JSON.parse(jsonString)];

How do I get div content as object

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.

Can't get JSON properties to display via jQuery

For some reason I just can't seem to be able to display properties from this JSON string:
http://www.easports.com/iframe/fifa14proclubs/api/platforms/PS4/clubs/51694/members
I've sat here for the last 2-3 hours trying out different ways to select single properties such as the name of the first person in the array. A couple selectors I've tried:
$("#output").append(data.raw[0].176932931.name);
$("#output").append(data.raw[0][0].name);
I always get the same error. "data.raw[0] is undefined". The JSON string is valid, I'm able to output the whole string to my page using:
document.getElementById('output').innerHTML=data.toSource();
Parsing it into a JSON object gives me another error because it already is a JSON object. By using console.log(data) I'm able to view the JSON object properly in Firebug.
data is the name of the Javascript JSON object variable that is being returned from my YQL statement.
Please, if anyone could provide some examples as to how I should go about accessing the properties of the above JSON string, that would be great.
UPDATE:
Here's the callback function from my YQL statement:
function cbfunc(json)
{
if (json.query.count)
{
var data = json.query.results.json;
$("#output").append(data.raw[0]["176932931"].name);
}
You need to use bracket notation, as identifiers starting with digits are invalid
$("#output").append(data.raw[0]["176932931"].name);
as "176932931" is an integer key so you have to access like json["176932931"].
For example
data.raw[0]["176932931"].name
see fiddle here
.count isn't a property of a json object. Try this:
var something = {"raw":[{"176932931":{"name":"Shipdawg","blazeId":176932931,"clubStatus":0,"onlineStatus":0,"nucleusId":2266699357,"personaName":"Shipdawg"},"182141183":{"name":"Beks8","blazeId":182141183,"clubStatus":0,"onlineStatus":0,"nucleusId":2272736228,"personaName":"Beks8"},"219929617":{"name":"ChelseaFC_26","blazeId":219929617,"clubStatus":0,"onlineStatus":0,"nucleusId":2304510098,"personaName":"ChelseaFC_26"},"457588267":{"name":"Lazy__Rich","blazeId":457588267,"clubStatus":0,"onlineStatus":0,"nucleusId":2495578386,"personaName":"Lazy__Rich"},"517570695":{"name":"x0__andrew__0x","blazeId":517570695,"clubStatus":0,"onlineStatus":1,"nucleusId":2549150176,"personaName":"x0__andrew__0x"},"912396727":{"name":"mizz00-","blazeId":912396727,"clubStatus":0,"onlineStatus":1,"nucleusId":1000118566560,"personaName":"mizz00-"},"915144354":{"name":"MisterKanii","blazeId":915144354,"clubStatus":2,"onlineStatus":0,"nucleusId":2281969661,"personaName":"MisterKanii"}}]}
function cbfunc(json)
{
if (json.raw.length)
{
$("#output").append(json.raw["0"]["176932931"].name);
}
}
cbfunc(something);
Tell me if this works for you:
function cbfunc(json)
{
$each(json, function(key, object){
console.log(key, object);
});
var raw = query.results.json.raw;
console.log(raw );
// uncomment it if you want some extra check.
if (/*typeof data.raw !=='undefined' && */data.raw.length > 0)
{
//console.log(data.raw[0]["176932931"].name);
//$("#output").append(data.raw[0]["176932931"].name);
}
}
If this works for you there's no need to reference the object to data, simply use the object its self.
JS fiddle: http://jsfiddle.net/q8xL3/2/

How to properly decode a JSON string encoded using Html.Raw(Json.Encode(Model))?

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;

Convert some data into json format but not sure if its working

I'm trying to get the attributes of a div and trying to put it in a json format.
For example if I have a div and its attributes are:
api="something" data-page="5" data-tag="blah"
So I'm trying to put it in this format in json:
{"api":"getArticles","parameters":{"param1":"value 1","param2":value2... }}
Here's the code I've written so far, but I'm not sure if I'm doing it right because its return [object Object]. How do I check if what I'm doing is correct and see the json array in the above mentioned form?
JSfiddle link: http://jsfiddle.net/ithril/mCNbW/4/
var arr = $("div").get(0).attributes, attributes = [];
var l;
var attrinames;
var attrivalues;
var api;
for(var i = 0; i < arr.length; i++) {
if(arr[i].name.indexOf("data-")==0){
l=arr[i].name.lastIndexOf("data-",0)+"data-".length;
attrinames=arr[i].name.substr(l);
if(attrinames!="apicall"){
attrivalues=arr[i].value;
attributes.push({attrinames:attrivalues});
}
else
api=attrivalues;
}
}
var json=[]
json.push({"api":api,"parameters":attributes});
alert(json);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.7.2/jquery.min.js"></script>
<div class="divload" data-apicall="anything.php" link="" data-page="5" data-tag="stuff">
JSON.stringify(data) will serialize the data contained within the Object.
See updated jsFiddle.
Don't use alert(variable). Use console.log(variable) and use a debugger instead. Hit F12 and view the console tab to see the results of console.log(). Also, I'd avoid naming a variable json because there is a global object named JSON.
Build the JS object whatever you want, then pass it to a JSON stringtifier, like this one:
https://github.com/douglascrockford/JSON-js
Don't try to build yourself a stringfier, because you will make mistakes, is best to use libraries or something builting.
JSON format is text, and you are building a object, you need to serialize that object to text using the json format.
Normally it will look like that:
JSON.stringify(data)

Categories