1

I have a .json file stored in a local directory on my computer.

data.json
{ 
  "foo": "bar",
  "baz": "bat"
}

I want to load data.json as arguments somehow into a .js file that I also have stored locally on my computer. Then run it.

app.js
var foo = "bar",
    baz = "bat"; // Somehow, I need to import these arguments from data.json
// Then do stuff with them...

app.js is a pure javascript file (without access to an HTML "wrapper" or any JS libraries like jQuery, etc.).

I would like to use one of the following to call app.js:

  1. Command line / shell script (including but not necessarily node.js),
  2. AppleScript (Mac OS X Yosemite v.10.10.1), or
  3. iMacros for Firebox bookmarklet.

How can I accomplish this?

3
  • 3
    What about updating data.jsonso that it looks like data = { ... }then adding <script type="text/javascript" src="data.json"></script> and then saying var mydata = JSON.parse(data);? Commented May 10, 2016 at 13:42
  • @fedorqui: I like the thought process. But would this really work as the question describes "without an HTML wrapper?" AFAIK, the <script> tag is only useable in HTML files not pure JS, correct? Commented May 10, 2016 at 14:04
  • Uhms, I guess you are right (I am not very familiar with JavaScript in general). Would this approach help you? Load JSON file locally using pure Javascript. It uses an XMLHttpRequest. Commented May 10, 2016 at 14:09

1 Answer 1

2

If you are using node, just require the json.

// app.js
var data = require('./data.json');
var foo = data.foo // etc

In your command line you can just run

node app.js

Of course if your data json is in a different directory, adjust the path accordingly. You could also allow it to use any json by providing it as an argument (see here)

Sign up to request clarification or add additional context in comments.

1 Comment

I'm not using any library; op is happy with using node. please don't downvote just because you don't understand the question

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.