答案 0 :(得分:0)
您可以使用以下内容:
{{1}}
答案 1 :(得分:0)
require
导入JSON。 (请参见Ben Nadel's explanation。)
通常,您希望将其存储为全局变量,而不是在每个keyup
事件中重新加载它。因此,如果JSON另存为watchlist.json
,则可以添加
var watchlist = require('./watchlist');
位于代码顶部。然后可以将搜索命令编写为(不需要for
循环):
kitten = kitten.toLowerCase();
if (watchlist.entities.indexOf(kitten) !== -1) {
alert('potential watchlist');
}
答案 2 :(得分:0)
在最新版本的Node中,您只需使用导入即可!
常见问题解答:
const jsonContent = require('path/to/json/file.json')
ES6:
import jsonContent from 'path/to/json/file.json'
您还可以通过以下示例动态导入JSon文件:
if (condition) {
const jsonContent = require('path/to/json/file.json')
// Use JSon content as you prefer!
}
那样,只有真正需要时才加载JSon文件,并且代码会获得更好的性能!
您喜欢老式的方法吗?
ES6:
import fs from 'fs' // or const fs = require('fs') in CommonJs
const JSonFile = fs.readFileSync('path/to/json/file.json', 'utf8')
const toObject = JSON.parse(JSonFile)
// read properties from `toObject` constant!
希望它会有所帮助:)