Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
166 views
in Technique[技术] by (71.8m points)

Importing a JSON file in Meteor

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

question from:https://stackoverflow.com/questions/15374066/importing-a-json-file-in-meteor

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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

The first is to store it as a JS Object

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.

Using an http call

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

Server Side code

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

Client Side Code

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

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.

Read the file directly

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"));

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


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

2.1m questions

2.1m answers

60 comments

57.0k users

...