繁体   English   中英

如何使用node.js将不同的json文件加载到不同的json对象中

[英]How to load a different json file into different json object using node.js

我是Json和node.js的新手

我正在尝试使用node.js将json文件加载到jsonobject中。 但是我做不到。

我创建了2个文件,其中一个是server.jsjsonresponse.json 我需要使用javascript或node.js在server.js创建的json对象中加载jsonresponse.json 这是server.js片段

var file = 'jsonresponse.json'
jsonfile.readFile(file, function(err, obj) {

       jsonObject = console.dir(obj);
 })

假设我的json数据在myDirectry/data.json

//data.json
{
    "a":2,
    "b":3
}

所以我的myDirectory/app.js应该是。

var x=require('./data');//or require('data');
console.log(x);

为了读取,尽管您可以使用fs读取,但仅require()就足够了。但是最好的方法是require

尽管以下代码将以过程方式为您提供对象,但您应牢记节点的异步行为。

   var jsonfile = require('jsonfile')
   var file = 'jsonresponse.json'
   var jsonObject = jsonfile.readFileSync(file)

从节点开始,您应该熟悉回调模式

在您提供的代码段中,文件正在回调中加载,您应该可以在该范围内访问。

   var file = 'jsonresponse.json';
   var jsonObject;
   jsonfile.readFile(file, function(err, obj) {
       //on success obj is the data therefore it holds the reference to contents of the file
       if(!err){
            jsonObject = obj;
       }
       else console.log(err);
   })

jsonfile.readFile与文件名和回调函数一起调用。 完成读取文件的任务后,它将使用两个参数调用回调函数: errordata

如果没有问题,则error为null,否则包含错误详细信息。

data包含函数要返回的任何数据。

如果您需要避免缓存(调用之间的文件更改),请执行此操作

var fs = require('fs')
var obj = JSON.parse(fs.readFileSync('myfile.json').toString())

暂无
暂无

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

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