提取本地JSON [英] Fetching local JSON
问题描述
如何获取目录中的本地JSON文件?
How can I fetch a local JSON file that is in my directory?
JSON文件如下所示:
the JSON file looks like this:
[
{
"name": "Sara",
"id": 3232
},
{
"name": "Jim",
"id": 2342
},
{
"name": "Pete",
"id": 532532
}
]
如果我在尝试使用的同一个文件中包含json信息,则效果很好,但是如果我想将其引入,那么我就无法一辈子让它正常工作并保持读为未定义.
If I have the json information inside the same file I'm trying to use it, it works beautifully, but if I want to bring it in, I can't for the life of me get it to work and it keeps reading it as undefined.
这是我所拥有的
getData() {
var json_data = require('../services/contributors.JSON');
for (var i in json_data){
console.log('Name: ' + json_data[i]["name"])
}
}
您能看到我在做什么吗?我正在尝试让它做出反应,所以反应可能会有所不同吗?我不知道.任何帮助将不胜感激.谢谢!
Can you see what I'm doing wrong? I'm trying to get this into react so maybe react works differently? I don't know. Any help will be appreciated. Thank you!
推荐答案
尝试使用文件系统.不要以为从JSON文件中读取内容就是这样.
Try to use file system. Don't think reading from a JSON file works like that.
const fs = require('fs');
const json_data = require('../services/contributors.JSON');
fs.readFile(json_data, 'utf8', function (err, data) {
try {
data = JSON.parse(data)
for (let i in data){
console.log('Name:',data[i].name)
}
} catch (e) {
// Catch error in case file doesn't exist or isn't valid JSON
}
});
这篇关于提取本地JSON的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!