I have a archive.json file like below:
var archive = {
"archiveList" : [
{ url : "https://ddddd",
greetings : "blahblahblah"},
{ url :"https://ddd1",
greetings : "blahblah"},
.....
]
}
I use the var keyword because I want to read from static page.
Here is the problem. I want to read that file and update archivelist array. How can I parse this file?
=============================Add more info================================
What I'm trying to is two things.
In static page, Read json(or js object) data from static page and show up
In server with node.js, Read json and insert archiveList data
What I read is this : https://stackoverflow.com/a/18637657/6234242
First thing what I'm trying to is solved, but Second one is my problem.
When I use module.exports = {...}, First thing is not working.
=============================Add more info================================
When I load and parse archive.json file, console says below.
undefined:1
var archive = {
^
SyntaxError: Unexpected token v in JSON at position 1
at JSON.parse (<anonymous>)
2 Answers 2
I think you're confusing some concepts here, but what you're presenting is plain JS. You can require that file if it's in your filesystem. The only real change needed is that you export something from that file:
module.exports = {
"archiveList" : [
{ url : "https://ddddd",
greetings : "blahblahblah"},
{ url :"https://ddd1",
greetings : "blahblah"},
.....
]
}
After that you can, for example:
const archiveList = require('./archiveList.js')
That's about it. From the little information you've provided, this should be enough, but otherwise expand on your use case.
2 Comments
module.exports, first thing what i'm trying to is not working. The browser says Uncaught ReferenceError: module is not definedAssuming the file is local, use:
module.exports = {
"archiveList" : [
to export the object from the static file, then add
const list = require('./file.js')
to your application.
6 Comments
var fs = require('fs'); var obj = JSON.parse(fs.readFileSync('file', 'utf8')); for more information read: nodejs.org/api/fs.html
var myJson = require('path/to/file.json');doesn't work for you? what have you tried?export, and it isn't JSON, that wouldn't work.export, First thing what I'm trying to is not working