Importing a JSON file in Meteor

前端 未结 3 900
清歌不尽
清歌不尽 2020-12-07 17:41

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? Thank

3条回答
  •  青春惊慌失措
    2020-12-07 18:15

    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

提交回复
热议问题