JSON call error with d3js - json

I'm trying to replicate this example of a bar chart that transitions in d3js. However, when I input my data into the .json file I get the error "Cannot call method 'forEach' of undefined" so I'm pretty sure I'm calling the .json file incorrectly. I have correctly changed the names of my variables, which are dates instead of text, so maybe that's messing something up:
Here's my .json file:
[{"network":"ABC","2002":9860,"2003":10596,"2004":9989,"2005":12217,"2006":12281,"2007":11913,"2008":12265,"2009":11050,"2010":9595,"2011":9871,"2012":8339},
{"network":"AZA","2002":0,"2003":0,"2004":0,"2005":0,"2006":213,"2007":0,"2008":0,"2009":201,"2010":236,"2011":212,"2012":0},
{"network":"CBS","2002":13959,"2003":13856,"2004":13581,"2005":12843,"2006":13019,"2007":11726,"2008":11274,"2009":11812,"2010":12538,"2011":12284,"2012":10690}]
And how I've tried to call it:
var json
d3.json("data.json", function(error, result){
json = result;
var data = [];
json.forEach(function(d){
data.push({variable: +d['2002'], network: d['network']});
});
x.domain(data.map(function(d) { return d.network; }));
y.domain([d3.min(data, function(d) { return d.variable; }), d3.max(data, function(d) { return d.variable; })]);
Any help would be much appreciated!

Your D3js code does not have any error.May be the json file is unreachable(as per the code the json file should reside in same folder of the HTML file).
You can use "console.log(json);" just after the line "json = result;" if the data is read from the file u will find it in console of "FireBug" or "Developer tools"(in chrome)

You might have an older version of D3 than in the example. I ran into the same problem and found that my version of D3 did not have an error parameter on the json function so the first parameter passed (the error, which was null) was expected to be the JSON string. So the 2 solutions I found are:
(1) Switch the parameters to have the JSON first:
d3.json("data.json", function(result, error){ ...
or just remove the error parameter altogether.
(2) Update to d3.v3.js.

Thanks for the reporting this question ,
Your error is because of your json file is unreachable.

Related

Read a external json file in Neutralino app

How can I read a external json file to populate my HTML?
I read the docs and see "filesystem.readFile(string filename, function success(data), function error)" but I don't know how can I set to read the file or what is the right folder to put the file.
This code from the docs prints the data from the json file. Consider parsing the returned json. NOTE : the function should always be an "async" function or it won't work.
async function readMyjsonFile(){
let response = await Neutralino.filesystem.readFile({
fileName: './myFile.json'
});
console.log(`Content: ${response.data}`);
}
If you use jQuery you can use jQuery.getJSON() (https://api.jquery.com/jquery.getjson/).
jQuery.getJSON('relativePath/myFile.json',function(data){
//Do something with your json data
}
or
jQuery.getJSON('file:///absolutePath/myFile.json',function(data){
//Do something with your json data
}

How to read data from JSON file and display in emulator using phonegap?

I am trying to display some JSON data which is available in a .json file in my application. The data is available through the web browser, but I am unable to get the data when it comes to emulator. Could some one help me in fixing this.
I used ajax call (getJSON) to retrieve the file.
$.getJSON('../files/english.json', function (data) {
//using the data to display
});
To understand what the problem is, simply extend your code to get additional information.
var jqxhr = $.getJSON('../files/english.json', function (data) {
//using the data to display
})
.fail(function( jqxhr, textStatus, error ) {
var err = textStatus + ", " + error;
console.log( "Request Failed: " + err );
});
The fail() function will tell you where the problem is.
As far as I can see from these few information, the problem could be in the relative path.
Please also note that, according to the official documentation:
As of jQuery 1.4, if the JSON file contains a syntax error, the
request will usually fail silently.

Papa Parse reading CSV locally

Can someone point to or show me a working example of Papa Parse reading a csv file.
When I try to use :
Papa.parse(file, {
complete: function(results) {
console.log("Finished:", results.data);
}
});
the file name is returned in the array instead of the data within. None of the internet examples actually work. The official demo works correctl inspecting its code I cant find it making use of the above strangely.
As #Matt mentioned in his comment, the trick is not to pass a file name, but a file object. This also was not intuitive to me at first, so here is a quick solution:
var data;
function parse() {
var file = document.getElementById('myDOMElementId').files[0];
Papa.parse(file, {
header: true,
dynamicTyping: true,
complete: function(results) {
console.log("Finished:", results.data);
data = results.data;
}
});
}
Note that you have to call the results in this way when working with a local file. If you want to work with the results elsewhere, assign it to a global variable.
I have faced the same problem and it was solved by 2 actions:
1- Adding a callback function
2- connecting to a local oython server/changing browser's security settigns
Check this:
https://github.com/mrdoob/three.js/wiki/How-to-run-things-locally
I did not pass an object but a string with the file name/path and it worked for me.

Nodejs write json to a file

I just started learning nodejs. I am currently working with sockets and made chat program.
I want to save entire chat to a json file. Currently my code is this :
socket.on('chat', function (data) {
message = {user : data.message.user, message : data.message.message};
chat_room.sockets.emit('chat', {message: message});
jsonString = JSON.stringify(message);
fs.appendFile("public/chat.json", jsonString, function(err) {
if(err) {
console.log(err);
} else {
console.log("The file was saved!");
}
});
});
This is currently working perfect, but the json which is written in file is wrong.
This gave me a wrong json
{"user":"niraj","message":"hw r u?"}{"user":"ntechi","message":"hello"}{"user":"ntechi","message":"hw r u?"}
The above code is called when message is triggered. I want json in this format
{"user":"awd","message":"hw r u?","user":"ntechi","message":"hello","user":"ntechi","message":"hw r u?"}
Can anyone help me in this? Thanks in advance
The first set of wrong JSON is created because you are appending a piece of JSON to a file each time you get a message.
The second set of JSON is also wrong - each property name has to be unique.
Presumably you want something like:
[
{"user":"niraj","message":"hw r u?"},
{"user":"ntechi","message":"hello"},
{"user":"ntechi","message":"hw r u?"}
]
In which case the logic you need to use is:
Read data from file
Parse data as JSON and assign to a variable
In the event of an error, assign an empty array to that variable
push the message object onto the end of the array
stringify the array
Overwrite the file with the new string

Determining the location of a JSON parse error

I am creating a web application that allows a user to load data in JSON format. I am currently using the following function to read JSON files that I have saved on my local disk:
function retrieveJSON(url, callback)
{
// this is needed because FireFox tries to parse files as XML
$.ajaxSetup({ mimeType: "text/plain" });
// send out an AJAX request and return the result
$.getJSON(url, function(response) {
console.log("Data acquired successfully");
callback(response);
}).error(function(jqXHR, textStatus, errorThrown) {
console.log("Error...\n" + textStatus + "\n" + errorThrown);
});
}
This works perfectly for well-formed JSON data. However, for malformed data, the console log displays the following:
Error...
parsererror
SyntaxError: JSON.parse: unexpected character
This is almost entirely unhelpful because it does not tell me what the unexpected character is or what line number it can be found on. I could use a JSON validator to correct the file on my local disk, but this is not an option when the page is loading files from remote URLs on the web.
How can I obtain the location of any error? I would like to obtain the token if possible, but I need to obtain the line number at minimum. There is a project requirement to display an excerpt of the JSON code to the user and highlight the line where any error occurred.
I am currently using jQuery, but jQuery is not a project requirement, so if another API or JSON parser provides this functionality, I could use that instead.
Yeah, life with deadlines is never easy :).
This might help you out, after couple of hours googling around, I've found jsonlint on Git Hub. It looks promising, it includes a shell script that could be used on server side, and there is a browser JavaScript version of it that seems to be exactly what you were looking for.
Hope that this will help You.
i agree that life with deadlines is hard.
i'm incredibly happy that i don't have to live with deadlines, i'm my own boss.
so in search of a better solution to this problem, i came up with the following :
...
readConfig : function () {
jQuery.ajax({
type : 'GET',
url : 'config.json',
success : function (data, ts, xhr) {
var d = JSON.parse(data);
},
error : function (xhr, ajaxOptions, thrownError) {
if (typeof thrownError.message=='string') {
// ./config.json contains invalid data.
var
text = xhr.responseText,
pos = parseInt(thrownError.message.match(/position (\d+)/)[1]),
html = text.substr(0,pos)+'<span style="color:red;font-weight:bold;">__'+text.substr(pos,1)+'__</span>'+text.substr(pos+1, text.length-pos-1);
cm.install.displayErrorMsg('Could not read ./config.json :(<br/>'+thrownError+'<br/>'+html);
} else {
cm.install.displayErrorMsg('Error retrieving ./config.json<br/>HTTP error code : '+xhr.status);
};
}
});
},
...