JSON cyclic object value when posting data in ChartJS - javascript

I'm working with ChartJS to create charts with inputs from the user. It works fine showing the results for more than one dataset, but when I post the data with Javascript using JSON I get this error "cyclic object value". I've been not able to find an answer here, so I'm going to try to explain the issue the best I can.
This is the JS object (myChart.data.datasets) I'm posting, with two datasets from ChartJS:
Then I have a save() function which post that info (working fine for just one dataset) once the chart is done.
function save() {
let data = {
datasets: myChart.data.datasets
};
$.post('/save',
{
savedData: JSON.stringify(data),
color: document.getElementById("color").value,
...
}
)
}
I have no idea what's the cyclic object here, but I know the problem is with the content of myChart.data.datasets being posted. I've used some of the filters from other similar questions, but all them makes some of the data to be lost.
I use the same object to display the chart, which works perfectly with more than one dataset. The problem just happens when posting the data.
Any ideas about what it might be happening? Truly appreciate it, thanks!

This wasn't trivial at all. As many questions & answers regarding cyclic objects in JSON are posted, none of them are very especific about what the solution is. For example, those which use the replacer parameter of JSON.stringify() don't work at all (at least in this case), as the data will be loss.
So, for me the solution was dojox.json.href from the Dojo javascript library. Here's some documentation.
It's not the whole thing, but here's some code in case someone need it. First you serialize the object:
require(["dojox/json/ref"], function(){
let data = {
datasets: dojox.json.ref.toJson(...)
}
$.post('/save',
...
});
And then you deserialize it:
require(["dojox/json/ref"], function(){
data = dojox.json.ref.fromJson(...);
});
You can import the library just like this:
<script src="//ajax.googleapis.com/ajax/libs/dojo/1.13.0/dojo/dojo.js"></script>
This is the only way I've been capable to post the JSON object without loosing data.
Hope it helps!

Related

JSON Array Restful to textarea

I am working in some code for school and has spend a couple of days looking thru post's but can't find a solution, this is actually my first post and welcome everyone who take the time to help!
I am coding a restful JSON API which I can send the data to the web service, however when I tried to read it and send the data to a textarea, I either get [object, Object] or a 0 (which I think is the index for the array generated from the json).
This is my code for the read function:
function cargarInfo(){
$.get("http://localhost:8080/Lec09/miApi/acciones", function(data, status){
var personas = data.personas;
document.getElementById("info").value = personas;
});
}
When I debug on chrome I can see the Object and the values, I think this is a realy noob question however IDK why I can't figure it out, it is suposed to show the json {nombre:xxxx apellidos:xxxxx} data
You can use JSON.stringify() to stringify your JSON data:
document.getElementById("info").value = JSON.stringify(personas);

load json data to dataset in d3js

I am having json file like this. It contains some data.
[{\"Frequency\":\"Building 1\",\"Data\":[{\"Name\":\"Medicine\",\"Value\":46,\"Value1\":26,\"Value2\":22},{\"Name\":\"food\",\"Value\":32,\"Value1\":26,\"Value2\":12}]},{\"Frequency\":\"Building 2\",\"Data\":[{\"Name\":\"Medicine\",\"Value\":48,\"Value1\":26,\"Value2\":23},{\"Name\":\"food\",\"Value\":34,\"Value1\":33,\"Value2\":12}]},{\"Frequency\":\"Building 3\",\"Data\":[{\"Name\":\"Medicine\",\"Value\":57,\"Value1\":22,\"Value2\":24},{\"Name\":\"food\",\"Value\":42,\"Value1\":16,\"Value2\":11}]},{\"Frequency\":\"Building 4\",\"Data\":[{\"Name\":\"Medicine\",\"Value\":59,\"Value1\":26,\"Value2\":33},{\"Name\":\"food\",\"Value\":44,\"Value1\":26,\"Value2\":35}]},{\"Frequency\":\"Building 5\",\"Data\":[{\"Name\":\"Medicine\",\"Value\":62,\"Value1\":26,\"Value2\":11},{\"Name\":\"food\",\"Value\":48,\"Value1\":26,\"Value2\":3}]},{\"Frequency\":\"Building 6\",\"Data\":[{\"Name\":\"Medicine\",\"Value\":62,\"Value1\":26,\"Value2\":21},{\"Name\":\"food\",\"Value\":47,\"Value1\":26,\"Value2\":24}]},{\"Frequency\":\"Building 7\",\"Data\":[{\"Name\":\"Medicine\",\"Value\":58,\"Value1\":26,\"Value2\":22},{\"Name\":\"food\",\"Value\":43,\"Value1\":26,\"Value2\":22}]},{\"Frequency\":\"Building 8\",\"Data\":[{\"Name\":\"Medicine\",\"Value\":48,\"Value1\":26,\"Value2\":2},{\"Name\":\"food\",\"Value\":34,\"Value1\":26,\"Value2\":33}]}]
I want to store this json file into dataset in d3.js. or
I have given all data are static into my code. I want to give these data from json file to d3.js can any one give me example.
my expected result is
dataset = JSON.parse("[{\"Frequency\":\"Building 1\",\"Data\":[{\"Name\":\"Medicine\",\"Value\":46,\"Value1\":26,\"Value2\":22},{\"Name\":\"food\",\"Value\":32,\"Value1\":26,\"Value2\":12}]},{\"Frequency\":\"Building 2\",\"Data\":[{\"Name\":\"Medicine\",\"Value\":48,\"Value1\":26,\"Value2\":23},{\"Name\":\"food\",\"Value\":34,\"Value1\":33,\"Value2\":12}]},{\"Frequency\":\"Building 3\",\"Data\":[{\"Name\":\"Medicine\",\"Value\":57,\"Value1\":22,\"Value2\":24},{\"Name\":\"food\",\"Value\":42,\"Value1\":16,\"Value2\":11}]},{\"Frequency\":\"Building 4\",\"Data\":[{\"Name\":\"Medicine\",\"Value\":59,\"Value1\":26,\"Value2\":33},{\"Name\":\"food\",\"Value\":44,\"Value1\":26,\"Value2\":35}]},{\"Frequency\":\"Building 5\",\"Data\":[{\"Name\":\"Medicine\",\"Value\":62,\"Value1\":26,\"Value2\":11},{\"Name\":\"food\",\"Value\":48,\"Value1\":26,\"Value2\":3}]},{\"Frequency\":\"Building 6\",\"Data\":[{\"Name\":\"Medicine\",\"Value\":62,\"Value1\":26,\"Value2\":21},{\"Name\":\"food\",\"Value\":47,\"Value1\":26,\"Value2\":24}]},{\"Frequency\":\"Building 7\",\"Data\":[{\"Name\":\"Medicine\",\"Value\":58,\"Value1\":26,\"Value2\":22},{\"Name\":\"food\",\"Value\":43,\"Value1\":26,\"Value2\":22}]},{\"Frequency\":\"Building 8\",\"Data\":[{\"Name\":\"Medicine\",\"Value\":48,\"Value1\":26,\"Value2\":2},{\"Name\":\"food\",\"Value\":34,\"Value1\":26,\"Value2\":33}]}]");
inside the bracket my data should be come i dont know how to do this can any tell me how to do this.
before i tried this but it is not working.
d3.json("D3json.json", function(error, data) {
var datas = data;
})
here is my jsfiddle example: Click here to see the example
Thanks
Vinoth S
If I understood your question correctly, you are trying to dynamically load JSON data in contrast to having it hard-coded in your file.
Here is an example how to do it: http://bl.ocks.org/Jverma/887877fc5c2c2d99be10
In general, you have to execute the drawing part after you successfully loaded the data (within the callback function of d3.json())

Passing objects from NodeJS to client and then into KnockoutJS viewmodel

So thanks to SO I can pass an object from node to the client, but then getting it into a knockout view model is a bit awkward. These are the steps I have so far (I've included links to the relevant lines as they appear in my github project. Thought the context might help.):
Apply JSON.stringify and pass to the jade file
recipeJSON: JSON.stringify(recipe);
Wrap this in a function in a header script that just parses the JSON and returns the result
script
function getRecipeObject() {
var r = '!{recipeJSON}';
return JSON.parse(r);
}
Call this function and pass the result to a view model constructor
self.recipe = ko.observable(new Recipe(getRecipeObject()));
This works but is there a better way?
Question clarification (Edit): I feel step 2 shouldn't be necessary. Is there a way to directly pass the JSON from node to the Recipe() constructor, without the getRecipeObject() acting as an intermediate step? I tried passing recipeJSON in directly like so
self.recipe = ko.observable(JSON.parse('!{recipeJSON}'));
That doesn't work I think because its not a jade template and has no access to the variable.
According to the answer to this question rendering data into scripts is bad practice and I should instead make an XHR call on page load instead.
Edit
I just saw you linked a github repo! So you're already familiar with most of this...you even have an endpoint set up at /recipe/:id/view, so now I'm really confused...what isn't working out for you? Just the last step of deserialization using ko.utils.*?
Sorry about all the exposition -- I thought this was way more rudimentary than it actually was; I hope no offense taken there!
You really don't want to return a script to execute -- instead, treat this as a DTO: an object that just stores data (no behaviors). An example would be:
{
recipeID: 12,
reviewIDs: [42, 12, 55, 31],
rating: 4.2
recipeName: "A super tasty pie!"
}
This object (representation) is a projection -- a simplified version of the full data stored in the database.
The next step is to create an endpoint to access that data on the server. Let's assume you're using Express:
var app = express();
app.get('/recipes/:recipeID', function(req, res) {
var recipeID = req.params.recipeID;
// It would be cool if this existed, huh?
getRecipeAsync(recipeID, function(recipe) {
res.status(200).json(recipe);
});
});
If you send a GET request to your (hypothetical) application (let's say it's https://localhost:8080/recipes/12), you'll get json representing the (admittedly imaginary) recipe with ID 12.
You can accomplish getting the JSON with jQuery (or any other library that makes XHR nice and pretty)
var recipeID = 12;
$.ajax({
url: "/recipes/" + recipeID,
type: "GET"
}).then(function(recipe) {
console.log("Hey! I got the recipe: %O", recipe);
// Note: you might need to use ko.utils.fromJS(recipe) if the returned
// data is JSON that ISN'T deserialized into an object
var recipeObservable = ko.utils.fromJS(recipe);
});
That's about everything you need to know. Obviously, the devil's in the details, but that's basic idea; let me know if that helps!

Databinding to Windows 8 ListView

I'm having massive problems with databinding to a ListView in a Windows 8 app using Javascript.
Inside the "activated" event on default.js I have written some code to get some data from a web service and push it into an array. This bit works OK and the array is populated.
The problem I have is that the app won't recognise the data. I have this code in a page called inspections.html:
data-win-options="{itemTemplate: select('#imageTextListCollectionTemplate'),
itemDataSource: dataList.dataSource,
layout: {type: WinJS.UI.ListLayout}}
and then in the "activated" event I declare:
var dataList = new Array();
and push the data from the web service into this array. But at runtime I get an error that says something along the lines of "can't find dataSource on undefined dataList".
I've done some of the examples on the MS website and in one of them it creates a dummy dataset and references it from a namespace. I kinda think that what I'm missing here is a namespace too but I don't know what the namespace for default.js is. Or maybe I'm wrong and it's something totally different.
Please help - this is so fundamental (and should be easy) but I can't get my head around it.
Do you want to create datalist in HTML or javascript?
It seems you want to create it from JavaScript. Assuming that you have already pushed your data into array from your webservice, you only need to call:
var dataList = new WinJS.Binding.List(array);
now accessing dataList.dataSource is perfectly valid.
Also, to create the datalist you don't always need an array. You could probably start with an empty list and then keep inserting data directly into the data list from web services, like:
var dataList = new WinJS.Binding.List([]);
dataList.push(value1);
dataList.push(value2);
...
Hope it helps. Let me know if you have any more questions.
If you are getting troubled by assigning datasource in HTML side
Prefer js side like
var list = new WinJS.Binding.List(array here);
listView.itemDataSource = list.dataSource;
by using this you can easily go through the data which you are binding to ListView.

Linked Pie Chart using Flot 0.7 returns "undefined" links

I am trying to create a Flot pie chart with a link in each wedge, so I can direct users to the appropriate details page on clicking.
There is already a similar post at With flot, how can I create a linked pie chart that takes you to other web pages?. I tried the answer on that page with with Flot 0.7 to obtain pie wedges with hyperlinked labels. However, series.URL returns "undefined" in the labelFormatter function. How do I resolve this issue?
On a side note: Its my first time posting here. I tried to ask this obviously related question at the link above so I don't create a new question for the same issue. However, it was deleted by the moderator. Wouldn't it have helped other users reading that post who suffered from the same issue to find a resolution? Not complaining, just trying to understand the rationale (have read the FAQs/Guidelines for asking questions..) behind the deletion.
If you follow the code in your linked question, they get quite close to what you want. The problem (which trips up many people) is that the item in the plotclick function is not the same as the series object in your raw data. What you can do though, is refer back to your raw data using item.seriesIndex in plotclick:
//setup options
//setup data
var data = [
{
label: "Serie1",
data: 10,
url: "http://stackoverflow.com"},
...
];
//call plot
//setup plotclick
$("#placeholder").bind("plotclick", function (event, pos, item) {
alert(data[item.seriesIndex].url);
});
I don't have it following the link, but that should be easy for you to do.
Here is some sample code in full: http://jsfiddle.net/ryleyb/pq4Q4/
Side note answer: Generally they would prefer you ask a new question instead of piling into an old question with new sub-questions. Especially in an "answered" question (I put answered in quotes because it doesn't seem that they came to a full answer, so I can see your confusion).

Categories

Resources