Javascript 获取本地 JSON
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/49481934/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Fetching local JSON
提问by PepperAddict
How can I fetch a local JSON file that is in my directory?
如何获取我目录中的本地 JSON 文件?
the JSON file looks like this:
JSON 文件如下所示:
[
{
"name": "Sara",
"id": 3232
},
{
"name": "Jim",
"id": 2342
},
{
"name": "Pete",
"id": 532532
}
]
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.
如果我在同一个文件中有 json 信息,我正在尝试使用它,它运行得很好,但如果我想把它带进来,我一生都无法让它工作,它会继续阅读它不明确的。
here is what I have
这是我所拥有的
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!
你能看出我做错了什么吗?我试图让它成为反应所以也许反应的工作方式不同?我不知道。任何帮助将不胜感激。谢谢!
采纳答案by Ben E
Try to use file system. Don't think reading from a JSON file works like that.
尝试使用文件系统。不要认为从 JSON 文件中读取数据是这样的。
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
}
});
回答by Ayeksius
Use fetch
用 fetch
fetch("../services/contributors.JSON")
.then(res => res.json())
.then(data => console.log(data))
I hope this helps
我希望这有帮助
回答by Nathan Ridley
You'll need to run your web page from a web server, due to browser security restrictions. You can do that very easily by making sure you first have Node.js installed, then installing a simple development server:
由于浏览器安全限制,您需要从 Web 服务器运行您的网页。通过确保首先安装 Node.js,然后安装一个简单的开发服务器,您可以很容易地做到这一点:
npm install -g http-server
Then from your console/terminal, navigate to the directory with your code in it, and run:
然后从您的控制台/终端,导航到包含您的代码的目录,并运行:
http-server
Finally, update your JavaScript code to load it like you'd do with any other server call:
最后,更新您的 JavaScript 代码以像处理任何其他服务器调用一样加载它:
async function loadJSON (url) {
const res = await fetch(url);
return await res.json();
}
loadJSON('../services/contributors.JSON').then(data => {
console.log(data[0].name);
});
and then load the page from http://localhost:8080(or whatever port you ran your http server on).
然后从http://localhost:8080(或运行 http 服务器的任何端口)加载页面。
回答by ak_azad
You can use fetchfor this
你可以用fetch这个
fetch('path to the json file')
.then(response => response)
.then(data => {
//do whatever with your data
})

