简体   繁体   English

如何使用require('./ data.js')读取Node.js中的JSON对象数组

[英]How to read an array of JSON objects in Node.js using require('./data.js')

The data stored is in data.js file (not JSON) and it is an array of objects. 存储的数据在data.js文件(不是JSON)中,并且是对象数组。 As an example, 举个例子,

 [
    {"id":"u4cse101", "name":"supriya","batch":"b"},
    {"id":"u4cse102", "name":"rahul", "batch":"a"},
    {"id":"u4cse345", "name":"ahalya", "batch":"a"}
 ]

I tried many methods, but couldn't achieve. 我尝试了许多方法,但无法实现。 Your help will be appreciated. 您的帮助将不胜感激。 UPDATE: One solution found is have the following in data.js file 更新:找到的一种解决方案是在data.js文件中data.js以下内容

JOURNAL = [
  {"x":"y"},
  {"a":"a"}
];
if (typeof module != "undefined" && module.exports)
  module.exports = JOURNAL;

and use the variable JOURNAL in another javascript file directly using require('./data.js') . 并直接使用require('./data.js')在另一个JavaScript文件中使用变量require('./data.js') But I am getting error: 但我得到了错误:

if (typeof module != "undefined" && module.exports)
^^

SyntaxError: Unexpected token if

you can save your json data file as data.json and use require to import json file 您可以将json数据文件另存为data.json并使用require导入json文件

var jsn = require("./data.json");
jsn = JSON.parse(jsn);

//data.json
[
{"x":"y"},
{"a":"a"}
];

It's easy, you can follow this approach. 很简单,您可以遵循这种方法。

var fs = require('fs');
var obj;
fs.readFile('data.js', 'utf8', function (err, data) {
  if (err) throw err;
  obj = JSON.parse(data);
});

Hope it resolve your issue :) 希望它能解决您的问题:)

You can use like this 你可以这样使用

var fs = require('fs');
fs.readFile('data.js', 'utf8', function(error, data) {
    data = JSON.parse(data);
})
//or
var data = fs.readFileSync('data.js', 'utf8');

I solved the problem. 我解决了问题。 The file should be 该文件应为

JOURNAL = [[
  {"x":"y"},
  {"a":"a"}
]];

instead of 代替

JOURNAL = [
  {"x":"y"},
  {"a":"a"}
];

data.json file data.json文件

{
"firstname:"abc",
"lastname":"xyz"
}

And then your route.js file you can include data.json file and print the data value like that: 然后,您的route.js文件中可以包含data.json文件,并按如下所示打印数据值:

var fs = require('fs'), obj

// Read the file and send to the callback fucntion
fs.readFile('path of data.json file', fileHandler)

// Write the callback function

function fileHandler(err, data) {

    if (err) throw err
    obj = JSON.parse(data)
    // You can now play with your datas
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM