简体   繁体   中英

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?

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.

所以最后我在JSON.stringify的结果上使用了console.log ,然后将内容复制/粘贴到外部json文件中......

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM