How can I replace outer object with an array? - javascript

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);
}

Related

jquery returning json data as undefined and images are not loading

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);
});

How to Get data in Json using javascripts?

Hi I'm currently creating an application to gather data form a website, and as I've researched you can used Json for that, now I have created a script to gather data, at first i have no problem with it, but when I cam across with a multi tree json i started having trouble.
here is my Json
{
"orders": [
{
"line_items": [
{
"id": 7660469767,
"name": "Personalised design - purple",
"properties": [
{
"name": "personalised text 1",
"value": "2"
},
{
"name": "personalised text 2",
"value": "Nuri &"
},
{
"name": "personalised text 3",
"value": "Samira"
}
],
}
]
}
]
}
I need to get the order.line_items.properties.value.
I tried this code but it says it does not work.
$.getJSON(order.json, function (data) {
$.each(data.orders.line_items.properties, function (index, value) {
$.each(this.value, function () {
console.log(this.text);
});
});
});
Can someone help me?
$.each(data.orders[0].line_items[0].properties, function (index, value) {
console.log(value.value);
});
Both orders and line_items are array, so it should have an access to array index first before accessing other object. And you don't have to use extra each in your code. The value above is an object for each properties. You can retrieve value there.

Assigning variable with $.getJson

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;
});

How to escape commas in JSON for read by highchart

I have the following JSON, I want add commas in between the numbers, but when ever I do that the JSON fails. My workign version of the code can be seen in the fiddle link below
FIDDLE
I want to change this 11488897 to 11,488,897
Is this possible to do? How can this be done?
thanks for your help
[{
"name": "",
"data": ["Totals","Total1 ","Total 2","total 3" ]
}, {
"name": "Amount1",
"data": [48353330,38079817,37130929,1957317]
}, {
"name": "Amount2",
"data": [11488897,8902674,8814629,497369]
}]
If you want to preserve commas, you just need to use strings:
"data": ["48,353,330","38,079,817","37,130,929","1,957,317"]
Whether that's a good idea or not is another story. Typically you'd want your JSON returned by the server to include raw (i.e., integer) data, and then just format it however you want when you're actually using it. That way the same RPC endpoint can be used to fetch data for use in a chart or for any other purpose that might arise later on.
try this:
var data = [{
"name": "",
"data": ["Totals","Total1 ","Total 2","total 3" ]
}, {
"name": "Amount1",
"data": [48353330,38079817,37130929,1957317]
}, {
"name": "Amount2",
"data": [11488897,8902674,8814629,497369]
}];
data.forEach(function(obj) {
obj.data = obj.data.map(function(item) {
if (typeof item == 'number') {
return item.toString().replace(/\B(?=(\d{3})+(?!\d))/g, ",");
} else {
return item;
}
});
});
alert(JSON.stringify(data, true, 4));
I don't know if it's cross-browser but if you do this
var number = 11488897;
number = number.toLocaleString('en');
You'll get the number (string) with commas on decimals

Backbone .fetch() adds one too many models

I am using backbone's fetch method to retrieve a set of JSON from the server. Inside the fetch call, I have a success callback that correctly assigns attributes to a model for each object found.
var foo = assetCollection.fetch({
reset: true,
success: function(response){
var data = response.models[0].attributes.collection.items;
data.forEach(function(data){
assetCollection.add([
{src_href: data.data[0].value,
title: data.data[1].value
}
]);
});
console.log(assetCollection.models)
}
})
Right now I am working with a static set of JSON that has two objects. However, logging assetCollection.models returns three objects: the first is the initial server JSON response, while the next two are correctly parsed Backbone models.
How do I keep Backbone from adding the first object (the entire response from the server) to its set of models, and instead just add the two JSON objects that I am interested in?
The JSON object returned from the server is as follows:
{
"collection": {
"version": "1.0",
"items": [
{
"href": "http://localhost:8080/api/assets/d7070f64-9899-4eca-8ba8-4f35184e0853",
"data": [
{
"name": "src_href",
"prompt": "Src_href",
"value": "http://cdn.images.express.co.uk/img/dynamic/36/590x/robin-williams-night-at-the-museum-498385.jpg"
},
{
"name": "title",
"prompt": "Title",
"value": "Robin as Teddy Roosevelt"
}
]
},
{
"href": "http://localhost:8080/api/assets/d7070f64-9899-4eca-8ba8-4f35184e0853",
"data": [
{
"name": "src_href",
"prompt": "Src_href",
"value": "http://b.vimeocdn.com/ts/164/830/164830426_640.jpg"
},
{
"name": "title",
"prompt": "Title",
"value": "Mrs. Doubtfire"
}
]
}
]
}
}
You should modufy collection.
Probably you should change parse method:
yourCollection = Backbone.Collection.extend({
parse: function(data) {
return data.models[0].attributes.collection.items;
}
})
When you use fetch Backbone parse result and add all elements what you return in parse.

Categories

Resources