Search code examples
javascriptarraysjsonwebstormdata-storage

Storing an array of objects in external JSON file


I have an array of objects in my javascript code that I would like to store as an external JSON file, more specifically in Webstorm's package.json. How can I achieve that? All the answers I find are related to the opposite - getting data from an external JSON file.

Here's the example of javascript array:

var questions = [{
        question: "Question1",
        choices: ["Choice1", "Choice2", "Choice3", "Choice4"],
        corAnswer: 0
    }, {
        question: "Questions2",
        choices: ["Choice1", "Choice2", "Choice3", "Choice4"],
        corAnswer: 1
    }, {
        question: "Question3",
        choices: ["Choice1", "Choice2", "Choice3", "Choice4"],
        corAnswer: 3
    }];

I guess the first thing to do would be JSON.stringify, but how do I then store it in package.json?


Solution

  • You can't write to files via Javascript, as others have said, but if you just want to store JSON objects in a different file and don't need to change the files, just throw them in a .js file and call that file in script tags before you call your main JS file. As long as it's in the global scope, the questions object will be available to methods in other files.