在 Meteor 中导入 JSON 文件 [英] Importing a JSON file in Meteor

查看:24
本文介绍了在 Meteor 中导入 JSON 文件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个 data.json 文件,我想加载它,并将它放在 lib/文件夹中.我应该怎么做才能将该 JSON 加载到服务器中的变量中?谢谢

I have a data.json file that I would like to load and that I have placed in the lib/ folder. What should I do in order to load that JSON into a variable in the server? Thanks

推荐答案

您可以通过三种方式解决这个问题,这取决于您最喜欢哪种方式 &您的用例.

There are three ways you can go about this, it depends what you're most comfortable with & your use case.

首先是将它存储为一个JS Object

如果你的 json 数据是 { "name":"bob" } 你可以在 中使用 myjson = {"name":"bob"}.js 文件位于 /lib 文件夹中,只需在需要时调用 myjson 即可.

if your json data is { "name":"bob" } you could use myjson = {"name":"bob"} in a .js file in the /lib folder and just call myjson when you need it.

使用 http 调用

您需要 Meteor http 包,通过 meteor add http 安装.

You need the Meteor http package, installed via meteor add http.

服务端代码

myobject = HTTP.get(Meteor.absoluteUrl("/myfile.json")).data;

客户端代码

HTTP.get(Meteor.absoluteUrl("/myfile.json"), function(err,result) }
    console.log(result.data);
});

另一种方法是获取 json 文件 ajax 样式(尽管您必须将其放在 /public 文件夹中并使用 Meteor.http 调用

Another way to do it is to fetch the json file ajax style (you would have to put it in your /public folder though and use Meteor.http to call it.

直接读取文件

最后,您可以直接读取文件,将 myfile.json 存储在项目根目录的 private 目录中:

Lastly you could read the file directly, you store your myfile.json in a private directory in your project's root:

var myjson = {};
myjson = JSON.parse(Assets.getText("myfile.json"));

如果你想在客户端访问它,你必须将它与 Meteor.methods 和 Meteor.call 接口

If you want to access this on the client side you would have to interface it with a Meteor.methods and Meteor.call

所以无论你想要哪种方式,第一种是最简单的,但我不太确定你想如何使用它,或者你是否想选择文件或其他东西

So whichever way you want, the first is the easiest but I'm not too sure how you want to use it or whether you want to pick the file or something

这篇关于在 Meteor 中导入 JSON 文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆