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?

Let Me Tink About It
  • 15,156
  • 21
  • 98
  • 207
  • 3
    What about updating `data.json`so that it looks like `data = { ... }`then adding `` and then saying `var mydata = JSON.parse(data);`? – fedorqui May 10 '16 at 13:42
  • @fedorqui: I like the thought process. But would this really work as the question describes "without an HTML wrapper?" AFAIK, the ` – Let Me Tink About It May 10 '16 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](http://codepen.io/KryptoniteDove/post/load-json-file-locally-using-pure-javascript). It uses an XMLHttpRequest. – fedorqui May 10 '16 at 14:09

1 Answers1

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)

Community
  • 1
  • 1
Andrei Nemes
  • 3,062
  • 1
  • 16
  • 22
  • I'm not using any library; op is happy with using node. please don't downvote just because you don't understand the question – Andrei Nemes May 10 '16 at 14:02