I am creating a chart with nvd3. Since i am pretty new to javascript i've got a little problem assigning the chartdata.
When i assign it like this:
var long_short_data = [
{
"key": "ISP",
"color": "#d62728",
"values": [
{
"label" : "oäop" ,
"value" : 9000
} ,...
]
},
{
"key": "Organization",
"color": "#d67548",
"values": [
{
"label" : "amklöericalököky" ,
"value" : 8000
},...
]
}
];
The graph is displayed as it should.
But when i assign it like this:
var long_short_data = $.getJSON( "/link/to/multiBarHorizontalData.json", function() {
console.log( "success" );
})
It doesnt.
These are my console logs:
success
nvd3.js:9229 Uncaught TypeError: data.map is not a function
Any help appreciated, thanks in advance
$.getJSON doesn't return result as you are expecting. It returns data in callback. It should be
$.getJSON( "/link/to/multiBarHorizontalData.json", function(result) {
long_short_data = result;
});
Related
I am trying to gain access within the last array of the json file and return the value from the "data" array of the json file and put it into the choiceSelection array. However, on my local host, it returns an undefined value and the images would not load. Can anyone help me out? I apologise if I haven't clearly explained my problem/logic and so please ask me for more details, if you're not sure. Thanks!
javascript code
$.getJSON('data.json', function(json) {
if(json[2].data){
for (i = 0; i < json[3].data.length; i++) {
choiceSelection[i] = new Array;
choiceSelection[i][0] = json[2].data[i].question;
choiceSelection[i][1] = json[2].data[i].correctChoice;
choiceSelection[i][2] = json[2].data[i].choice1;
choiceSelection[i][3] = json[2].data[i].choice2;
}
// choiceSelection.length = choiceSelection.length;
displayQuestion();
console.log(json[2]);
}
})
json file
[
{
"name": "match numbers 1",
"template": "matching",
"data": [
[
"six",
"Images/Number6.jpg"
],
[
"eight",
"Images/Number8.jpg"
],
[
"nine",
"Images/Number9.jpg"
]
]
},
{
"name": "order numbers 1",
"template": "ordering",
"data": [
[
"Images/Number6.jpg"
],
[
"Images/Number8.jpg"
],
[
"Images/Number9.jpg"
]
]
},
{
"name": "animal",
"template": "picture game",
"data": [
{
"question": "Where is the cat?",
"correctChoice": "Images/5cats.jpg",
"choice1": "Images/squirrel.png",
"choice2": "Images/beagle.png"
},
{
"question": "Where is the cat?",
"correctChoice": "Images/5cats.jpg",
"choice1": "Images/squirrel.png",
"choice2": "Images/beagle.png"
}
]
}
]
Edit 1: change json[i] to json[2].data. Still undefined
Edit 2: changed json[2].data. to json[2].data[i] and used json[3].data.length in the for statement. It works perfectly now. Thank you everyone for the help!:)
You could take the hassle out of your code and use some ES6 destructuring to get at your data more easily.
const json = '[{"name":"match numbers 1","template":"matching","data":[["six","Images/Number6.jpg"],["eight","Images/Number8.jpg"],["nine","Images/Number9.jpg"]]},{"name":"order numbers 1","template":"ordering","data":[["Images/Number6.jpg"],["Images/Number8.jpg"],["Images/Number9.jpg"]]},{"name":"animal","template":"picture game","data":[{"question":"Where is the cat?","correctChoice":"Images/5cats.jpg","choice1":"Images/squirrel.png","choice2":"Images/beagle.png"},{"question":"Where is the cat?","correctChoice":"Images/5cats.jpg","choice1":"Images/squirrel.png","choice2":"Images/beagle.png"}]}]'
function getJSON(endpoint, callback) {
setTimeout(() => callback(JSON.parse(json)), 1000);
}
// grab the third object from the response data
getJSON('data.json', function([ ,,obj ]) {
// grab the data array from that object but relabel it
// `choiceSelection
const { data: choiceSelection } = obj;
// then use the object property keys to get access
// to the data instead of indexes. Much easier.
console.log(choiceSelection[0].question);
console.log(choiceSelection[1].question);
});
This question might already been asked but I'm having some trouble understanding it, I'd like to update my javascript object with new objects.
Object 1 :
var cjson = {};
var t = {
"infos": "apple",
"fields": {
"color":"red",
}
}
cjson['g320fld1'] = t;
Object 2 :
var data {
"fruits": {},
"vegetables": {}
}
Output : I want to push object 1 to object 2 under fruits key. so the ouput look :
{
"fruits": {
"g320fld1": {
"infos": "apple",
"fields": {
"color":"red",
}
},
"vegetables": {}
}
What I tried :
push()
data['fruits'].push(cjson);
Error : ...push() is not a function. (I know push() works on array only so it won't work here.)
update()
data['fruits'].update(cjson);
Error : ...update() is not a function. (this one gives the same error but since it's another dictionary shouldn't it work as expected ?)
How can I solve this problem ?
UPDATE :
Sorry I didn't precise, I don't want to erase older data in fruits.
You can just assign t with the key directly to the data object. As long as your keys(g320fld1 for example) are distinct nothing will be overwritten. I think this makes more sense for what you are trying to do.
var t = {
"infos": "apple",
"fields": {
"color":"red",
}
}
var data = {
"fruits": {},
"vegetables": {}
}
data.fruits['g320fld1'] = t;
console.log(data);
EDIT
You can use Object.assign(srcObject,newProperties) to append new properties,values to an existing object.
var cjson = {};
var t = {
"infos": "apple",
"fields": {
"color":"red"
}
}
cjson['g320fld1'] = t;
var data ={
"fruits": {
otherProperty:"bar"
},
"vegetables": {}
}
Object.assign(data.fruits,cjson);
console.log(data)
I'm trying to make a graph. S I need to send an ajax request, select some rows from database, then return the result. I did it. And here is the output:
success : function (data) {
console.log(data);
}
To make that graph, I need to convert my current output to this structure: (this structure is the one I should pass it to the library which draws the graph)
var json = [
{
"adjacencies": [
{
"nodeTo": "graphnode15",
"nodeFrom": "graphnode0",
"data": {}
},
{
"nodeTo": "graphnode16",
"nodeFrom": "graphnode0",
"data": {}
},
{
"nodeTo": "graphnode17",
"nodeFrom": "graphnode0",
"data": {}
}
],
"data": {
"$color": "#83548B",
"$type": "circle"
},
"id": "12",
"name": "sajad"
}
];
I've tested all of these:
console.log(data);
console.log([data]);
console.log(JSON.stringify(data));
console.log("["+JSON.stringify(data)+"]");
But none of them isn't expected structure for the library which draws the graph. Anyway, Does anybody know how can I make expected structure?
JSON.parse(data) will do this.
Try:
json =[]
json.push(data)
send this json to the graph
Maybe this should work
success : function (data) {
var json = [JSON.parse(data)];
console.log(json);
}
I'm trying to add data to the end of an observable array but it's just not working as expected. I bet it is something minor but I just can't get my head around it.
What I am doing:
self.businesses = ko.observableArray();
function Business(business) {
var self = this;
self.BusinessID = ko.observable(business.BusinessID );
self.Type = ko.observable(business.Type);
self.Location = ko.observable(business.Location);
}
/*ajax get array of businesses as follows:
[
{
"$id": "1",
"BusinessID ": 62,
"Type": "Data",
"Location": "Data"
},
{
"$id": "2",
"BusinessID ": 63,
"Type": "Data",
"Location": "Data"
},
{
"$id": "3",
"BusinessID ": 64,
"Type": "Data",
"Location": "Data",
} ]
*/
var mappedBusinesses = $.map(data, function (business) { return new Business(business) });
self.businesses(mappedBusinesses);
This all works as expected and the obersablearray is populated.
However if I go to add another business, it wont work. For example, if I call the ajax that returns this (as newBusiness):
{
"$id": "1",
"BusinessID ": 68,
"Type": "Data",
"Location": "Data"
}
and I do:
self.businesses().push(newBusiness);
It adds to the array as an "Object" not a Business. So I thought I would do:
var bus = $.map(newBusiness, function (business) { return new Business(business) });
self.businesses().push(bus);
But I get the error in the JS console "Uncaught TypeError: Cannot read property 'BusinessID' of null
So I made a new var and added the brackets: [] in and it adds to the observable array but not as a "Business" object but rather as an "Array[1]" object at the end and this doesn't function as per the others. Code as follows:
var newBus = {
BusinessID: newBusiness.BusinessID,
Type: newBusiness.Type,
Location: newBusiness.Location
}
var bus = $.map(newBus, function (business) { return new Business(business) });
self.businesses().push(bus);
As mentioned this adds to the observable array but doesn't actually add as a "business" object but rather as an "array[1]" object.
I bet it's something so basic but just can't get it working!
Argh I knew it would be simple!
It was posting the whole array to the ObservableArray...not just the object.
The fix:
self.businesses.push(newBusiness[0])
Had to add the [0] in to get it to push the actual data into the array, not the object!
Thanks for the answers!
You're evaluating the array with your push:
self.businesses().push(newBusiness);
Observable Arrays have their own array functions, you should just do this (no parens):
self.businesses.push(newBusiness);
See this page: http://knockoutjs.com/documentation/observableArrays.html
I know this is a very simple and common question; I've already read some Q/A but I can't figure out how to solve my problem.
I have this short json from an AJAX call that execute a SPARQL query:
{
"head": {
"vars": [ "name" , "email" ]
} ,
"results": {
"bindings": [
{
"name": { "type": "literal" , "value": "Name Surname" } ,
"email": { "type": "literal" , "value": "name.surname#email.com" }
}
]
}
}
I'm searching name and email of a single user of the application, so
the result should be always made up of a single element.
What I want to retrieve is the "name" of the user.
I tried something like:
response["name"].value
//or
response[0]["name"]
//or
response.name
but always wrong.
How can I get the name value? Thanks to everyone who will help.
Try this
response.results.bindings[0].name.value
response.results.bindings[0].email.value
Update
Example
You can check out the fiddle created here
http://jsfiddle.net/uqxp4j73/
The code for this is as under
var x='{ "head": { "vars": [ "name" , "email" ] } , "results": { "bindings": [ { "name": { "type": "literal" , "value": "aadil keshwani" } , "email": { "type": "literal" , "value": "name.surname#email.com" } } ] }}';
obj = JSON && JSON.parse(x) || $.parseJSON(x);
console.log(obj);
console.log(obj["results"]["bindings"][0]["name"]["value"]);
alert(obj["results"]["bindings"][0]["name"]["value"]);
Hope this helps :)
In JSON, you always have to provide the full path to the property you like to reach. Assuming you have stored the parsed JSON in variable response, the following paths will get you corresponding value.
response.results.bindings[0].name.value for name
response.results.bindings[0].email.value for email
Recommend you to go through http://www.copterlabs.com/blog/json-what-it-is-how-it-works-how-to-use-it/ to get basic concepts of JSON.