Openlayers & NPM: can't load local .json file - json

I try to load a .json file in Openlayers from a local URI. As recommended, I'm using npm. However, the file doesn't seem to load. The file example.json is stored in the directory data, which is a subdirectory of where the main.js is located. The json file I'm using is valid according to jsonLINT.
var vectorLayer = new VectorLayer({
source: new VectorSource({
url: 'data/example.json',
format: new GeoJSON()
}),
style: function(feature) {
style.getText().setText(feature.get('name'));
return style;
}
});
var map = new Map({
target: 'map',
layers: [ vectorLayer],
// ...
});
Messages in the console:
XHR GEThttp://localhost:1234/data/example.json [HTTP/1.1 200 OK 4ms]
SyntaxError: JSON.parse: unexpected character at line 1 column 1 of the JSON data
XHR GEThttp://localhost:1234/data/example.json [HTTP/1.1 304 Not Modified 14ms]
SyntaxError: JSON.parse: unexpected character at line 1 column 1 of the JSON data
I guess, the file doesn't load at all. If I change the adress to some file that isn't in the directory, I'll get the same messages. On reload, I'd get the 304 error code twice. If I type in 'localhost:1234/data/example.json' as URL, it'll retrieve my main page (as with localhost:1234), not the json file I'd expect to see.
I'm a beginner with npm so I assume the problem is how files are handled with npm.

Related

Error when trying to load local csv file in Vue3 app

I am trying to load a local CSV file with papaparse to extract it's content in a Vue3 application.
When I try something like:
let myTest = Papa.parse("#/assets/data/postcodes.csv", {
delimiter: ",",
header: true
});
I get a blank response as if the filepath is wrong. However, if I try importing the file directly with Vue3, so I can pass it to the papaparse method, like this:
import myFile from "#/assets/data/postcodes.csv"
...
let myTest = Papa.parse(myFile, {
delimiter: ",",
header: true
});
I get this error:
ERROR in ./src/assets/data/postcodes.csv 3:5
Module parse failed: Unexpected token (3:5)
You may need an appropriate loader to handle this file type, currently no loaders are configured to process this file. See https://webpack.js.org/concepts#loaders
| Suburb,Postcode
| Condobolin,2877
> Lake Cargelligo,2672
| Murrin Bridge,2672
| West Wyalong,2671
What is the correct way to reference a local csv file in the asset directory? I assume my file path is correct because of the error.
It hasn't been an issue loading other local assets like images and icons.

Importing JSON file in Cucumber Protractor framework

I want to keep my test data in a JSON file that I need to import in cucumber-protractor custom framework. I read we can directly require a JSON file or even use protractor params. However that doesn't work. I don't see the JSON file listed when requiring from a particular folder.
testdata.json
{
"name":"testdata",
"version":"1.0.0",
"username":"1020201",
"password":"1020201"
}
Code in the Config.js
onPrepare: function() {
var data = require('./testdata.json');
},
I don't see the testdata.json file when giving path in require though its available at the location.
I wish to access JSON data using data.name, data.version etc.
Following is my folder structure:
You should make sure your json file is located in the current directory & and in the same folder where your config file resides as you are giving this path require('./testdata.json'); -
There are many ways of setting your data variables and accessing them globally in your test scripts -
1st method: Preferred method is to use node's global object -
onPrepare: function() {
global.data = require('./testdata.json');
},
Now you could access data anywhere in your scripts.
2nd Method Is to use protractor's param object -
exports.config = {
params: {
data: require('./testdata.json');
}
};
you can then access it in the specs/test scripts using browser.params.data

Webpack 4 - JSON module not found

I have some JSON files in my Webpack application that I want to import. They have names such as 0.json, 1.json, 2.json, and so on and are inside of the directory src/res/level/. When I try to require() them in my code, it does not work:
private loadWorld() {
// load the level
// duplicate the object to avoid modifying the actual instance
// that json-loader created
this.state.level = JSON.parse(JSON.stringify(require(`#res/level/${this.level}.json`))) as LevelData;
// ...
}
This line in my method always throws an error:
Error: Cannot find module "#res/level/1.json".
at webpackContextResolve (webpack-internal:///9:16:11)
at webpackContext (webpack-internal:///9:9:11)
However, I cannot figure out why. And to make things more confusing, if I run Webpack in watch mode, and I edit this line before my program tries to run it, then the JSON files are suddenly loaded properly.
I have configured my alias for #res properly:
resolve: {
extensions: [".ts", ".js", ".glsl", ".json"],
alias: {
"#res": path.join(__dirname, "src/res"),
"#lib": path.join(__dirname, "src/lib"),
"#shader": path.join(__dirname, "src/shader"),
"#control": path.join(__dirname, "src/control"),
"#scene": path.join(__dirname, "src/scene"),
"#util": path.join(__dirname, "src/util"),
}
}
And because this is Webpack 4, I simply did not include a loader for JSON.
So why is this not working?
Additionally, I notice that when I inspect the generated code, I see this:
Which suggests that the JSON files are being loaded, but not under the directory that I expect.
The compiler began to load the JSON files consistently when I used string concatenation instead of a template string:
this.state.level = JSON.parse(JSON.stringify(require("#res/level/" + this.level.toString() + ".json"))) as LevelData;

Running json-2-csv npm using as input a json file saved to desktop

I try to use this from npm in order to convert a json file I have saved to my desktop.
However I can't understand how to do it because I am not an original programmer.
I have installed the npm and
npm install json-2-csv
after this steps I can't understand how can I import my json file.
If there is anyone who could help me with the following steps or screenshots it could be very very useful for me.
Thank you in advance.
Put your json file to root directory of your Node.js application and rename it to data.json.
Then create app.js file in the same directory with this code:
var converter = require('json-2-csv');
var fs = require('fs');
var jsonData = require('./data.json');
var json2csvCallback = function (err, csv) {
if (err) throw err;
fs.writeFile("./data.csv", csv, function(err) {
if(err) throw err;
console.log("data.csv file has been saved.");
});
};
converter.json2csv(jsonData, json2csvCallback);
It requires data.json file from the root app directory (will work only with a valid JSON, otherwise you will find an error description in the console). If all ok, it will convert JSON to CSV using json-2-csv module and will save data.csv file with the result still in the root app directory.
Just try to run it with: node app.js

JSON call error with d3js

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.