I looked up how to access a .json file without saving it to my code base but was not able to find it - all posts are like this one: How to acces external json file objects in vue.js app
where they assumed that I could save the .json file in the code base like so: import json from './json/data.json' - they are going to call it json, it is in json folder from the file named data.json.
In my case, on the contrary, when the user tries to read their own .json file saved in their windows file explorer's "Download" folder, there can be one or multiple files, and the user will select any one of them to be accessed and read by the website.
Me as a developer don't own the file that the user will select, don't know which file the user will choose, therefore don't know the name of the file or the file content, and so, I cannot have that file saved in the code base.
Is there a way for me to enable the user to select any .json file they want, have that accessed and read?
Thank you.
UPDATE: from the suggestions from the comment section, fileSelector appears as null in the dev tool
<input type="file" id="file-selector" accept="application/JSON" multiple>
interface HTMLInputEvent extends Event {
target: HTMLInputElement & EventTarget;
}
mounted() {
const fileSelector = document.getElementById('file-selector');
fileSelector.addEventListener('change', (event: HTMLInputEvent) => {
let files: any = event.target.files[0];
const fileList = event.target.files;
console.log(fileList);
});
}
Apparently you're using Typescript, so your error is at runtime or at build time?
the type of the event argument doesn't seem correct to me, try:
fileSelector.addEventListener('change', (event: Event) => {
const files = (e.target as HTMLInputElement).files
})
Related
Using Nuxt 3, I am struggling to do something that appears simple: I would like to get a list of restaurants from an api served by nuxt/nitro in order to use it on the client side. My original file, is a .csv file stored under assets/: assets/list.csv.
Here is what I have in my component .vuefile:
//...
const { restaurants } = await useFetch('/api/restaurants')
//...
And the content of server/api/restaurants.js:
import csv from 'csvtojson'
export default defineEventHandler(async(event) => {
const data = await csv().fromFile('~/assets/list.csv')
return { data }
})
But I get an error "[500] File does not exist". I've tried many variants but always get an error here or there. Could you help me figure out the solution? Thanks.
Actually solved by realizing the following:
As the doc suggests, the assets/ directory is for assets that are processed by the bundler (Vite or Webpack). Nuxt won't serve files in the assets/ directory unless nuxt.config.ts is configured with the appropriate loader (e.g. a csv loader). Hence the 500 error.
Nuxt Content, on the other hand, is useful to automatically parse a .csv file located in the content/ directory:
In nuxt.config.ts:
modules: ["#nuxt/content"]
In the component .vue file, the following will expose the parsed csv in data.body:
const { data } = await useAsyncData("list", () => queryContent("/list").findOne())
The beauty of nuxt is that you don't need to import anything, it does it for you.
My svelte app is required to read json file from the public folder.
I followed exactly the rollup setup from this link, then add json to my app.svelte:
import * as port from '/port.json';
port.json is located at the public folder together with index.html.
But I keep getting this error:
main.js:11 Uncaught ReferenceError: port is not defined at main.js:11
and I am getting this message from Terminal which I am not sure what it means:
(!) Missing global variable name Use output.globals to specify browser
global variable names corresponding to external modules /port.json
(guessing 'port')
How can I resolve this?
You have two options.
Move the file to your src/ folder and bundle it with the rest of your application code using Rollup. This is where you need #rollup/plugin-json to bundle json files. You can then import it like so:
<script>
import json from './port.json';
</script>
<p>{JSON.stringify(json)}</p>
Keep the file in your public/ folder and retrieve it at runtime using fetch.
<script>
let fetchJson = fetch('port.json').then(res => res.json());
</script>
{#await fetchJson}
<p>Loading JSON</p>
{:then result}
<p>{JSON.stringify(result)}</p>
{/await}
Export the object and rename the file from .json to .json.js.
port.json.js
export let myJson = {
name: "hello world"
}
Component:
<script>
import json from './port.json';
</script>
<p>{JSON.stringify(json)}</p>
I am using lib in npm for project angular call json2csv for export JSON to file.csv (excel)
Here is my code:
const fields = ['id', 'name'];
const opts = { fields };
try {
const parser = new json2csv.Parser(opts);
const csv = parser.parse(this.data);
console.log(csv);
} catch (err) {
console.error(err);
}
Printing object is correct data but not create file.
Can anyone help me when add filename and path in my code?
The json2csv node_module that you're trying to use in your Angular App is not supposed to be used there. It's supposed to be used on your NodeJS backend.
Your Frontend/Client is not responsible for writing files to the system. Your Backend/Server is.
Ideally, you should be creating a REST API to which, you'll be passing the JSON to be written in a CSV file as a Request Payload.
Your NodeJS Backend can then respond to that request with the downloadable CSV file that is generated by using the json2csv node_module
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
In my Vue project, I have mocked some data for next step development. I already save the test data in a json file. And my vue project is typical one created with Vue-Cli, and the structure for my project goes as following:
My_project
build
config
data
service_general_info.json
node_modules
src
components
component-A
component-A.vue
as you can see, all the folders are created by the vue-cli originally. And I make a new folder data and place the test data json file inside.
And I want to read in the data by axios library in an event handling function inside the component of component-A as following:
methods: {
addData() {
console.log('add json data...');
axios.get('./../../data/service_general_info.json');
},
},
I use relative path to locate the target file.But get 404 error back. So how to set the path correctly? Currently I am running the dev mode in local host.
The error message is: GET http://localhost:8080/data/service_general_info.json 404 (Not Found)
In Vue-cli project, axios can't get data from custom folder.
You should use static folder to save test json file.
So you should change axios call like this:
axios.get('/static/service_general_info.json');
This will get data from json.
If you are doing just for sake of testing then you can save it in public folder and access it directly on http root.
e.g. I have the file results.json in public folder then I can access it using http://localhost:8080/results.json
For me it didn't work using static folder. I had to put it in public folder.
I put json folder in public & then accessed it like below.
getCountries() {
return axios.get('json/country-by-abbreviation.json', { baseURL: window.location.origin })
.then((response) => { return response.data; })
.catch((error) => {
throw error.response.data;
});
}
When the http call is made from the server, axios has no idea that you're on http://localhost:8080, you have to give the full url.
Like this:
methods: {
addData() {
console.log('add json data...');
axios.get('http://localhost:8080/data/service_general_info.json');
},
},
I had this same issue, only the above solutions wouldn't work as it is being uploaded to a subdirectory. I found I needed to put it in the public/assets folder and use:
axios.get(process.env.BASE_URL+'assets/file.json')
While in vue.config.js I have set the local and live paths
module.exports = {
publicPath: process.env.NODE_ENV === 'production'
? '/path/to/app/'
: '/'
}
You can simply read a static JSON file using import. Then assign in data.
import ServiceInfo from './../../data/service_general_info.json';
export default{
data(){
return {
ServiceInfo
}
}
}