JavaScript에서 외부 로컬 JSON 파일을 읽는 방법은 무엇입니까?
JSON 파일을 로컬 시스템에 저장하고 JSON 파일을 읽고 데이터를 인쇄하기 위해 JavaScript 파일을 만들었습니다. JSON 파일은 다음과 같습니다.
{"resource":"A","literals":["B","C","D"]}
이것이 JSON 파일의 경로라고 가정 해 봅시다 /Users/Documents/workspace/test.json
.
누구나 JSON 파일을 읽고 JavaScript로 데이터를 인쇄하는 간단한 코드를 작성하도록 도와 줄 수 있습니까?
당신은 할 수없는 요청이 HTTP를 사용하여 만들어 같은 로컬 리소스에 AJAX 호출을합니다.
해결 방법은 로컬 웹 서버를 실행하고 파일을 제공하고 localhost를 AJAX 호출하는 것입니다.
JSON을 읽는 코드를 작성하는 데 도움이되는 관점에서 다음에 대한 설명서를 읽어야합니다 jQuery.getJSON()
.
http://api.jquery.com/jQuery.getJSON/
javascript를 사용하여 외부 로컬 JSON 파일 (data.json)을 읽으려면 먼저 data.json 파일을 작성하십시오.
data = '[{"name" : "Ashwin", "age" : "20"},{"name" : "Abhinandan", "age" : "20"}]';
자바 스크립트 파일과 함께 스크립트 소스에서 json 파일의 경로를 언급하십시오.
<script type="text/javascript" src="data.json"></script> <script type="text/javascript" src="javascrip.js"></script>
json 파일에서 객체 가져 오기
var mydata = JSON.parse(data); alert(mydata[0].name); alert(mydata[0].age); alert(mydata[1].name); alert(mydata[1].age);
자세한 정보는 이 참조를 참조 하십시오 .
.json
하드 디스크 에서 파일 을 로드 하는 작업은 비동기 작업이므로 파일을로드 한 후 실행할 콜백 함수를 지정해야합니다.
function readTextFile(file, callback) {
var rawFile = new XMLHttpRequest();
rawFile.overrideMimeType("application/json");
rawFile.open("GET", file, true);
rawFile.onreadystatechange = function() {
if (rawFile.readyState === 4 && rawFile.status == "200") {
callback(rawFile.responseText);
}
}
rawFile.send(null);
}
//usage:
readTextFile("/Users/Documents/workspace/test.json", function(text){
var data = JSON.parse(text);
console.log(data);
});
이 기능은로드 A에 대한 또한 작동 .html
또는 .txt
에 MIME 형식 매개 변수를 대체하여, 파일 "text/html"
, "text/plain"
등
- 먼저 json 파일을 작성하십시오. 이 예에서 내 파일은 words.json입니다.
[{"name":"ay","id":"533"},
{"name":"kiy","id":"33"},
{"name":"iy","id":"33"},
{"name":"iy","id":"3"},
{"name":"kiy","id":"35"},
{"name":"kiy","id":"34"}]
- 그리고 여기 내 코드, 즉 node.js가 있습니다.
'utf8'
인수에 유의하십시오readFileSync
: 이것은Buffer
(JSON.parse
처리 할 수는 있지만) 문자열이 아니라 문자열을 반환 합니다. 결과를 볼 수있는 서버를 만들고 있습니다 ...
var fs=require('fs');
var data=fs.readFileSync('words.json', 'utf8');
var words=JSON.parse(data);
var bodyparser=require('body-parser');
console.log(words);
var express=require('express');
var app=express();
var server=app.listen(3030,listening);
function listening(){
console.log("listening..");
}
app.use(express.static('website'));
app.use(bodyparser.urlencoded({extended:false}));
app.use(bodyparser.json());
- 특정 ID 세부 정보를 읽으려면 코드를 다음과 같이 언급 할 수 있습니다.
app.get('/get/:id',function(req,res){
var i;
for(i=0;i<words.length;++i)
{
if(words[i].id==req.params.id){
res.send(words[i]);
}
}
console.log("success");
});
- URL에 입력하면
localhost:3030/get/33
해당 ID와 관련된 세부 정보가 제공됩니다 .... 이름으로도 읽습니다. 내 json 파일에는이 코드가있는 비슷한 이름이 있습니다. 하나의 이름 세부 정보를 얻을 수 있습니다 .... 그리고 모든 유사한 이름을 인쇄하지는 않았습니다.
app.get('/get/:name',function(req,res){
var i;
for(i=0;i<words.length;++i)
{
if(words[i].id==req.params.name){
res.send(words[i]);
}
}
console.log("success");
});
- 그리고 유사한 이름 세부 정보를 읽으려면이 코드를 사용할 수 있습니다.
app.get('/get/name/:name',function(req,res){
word = words.filter(function(val){
return val.name === req.params.name;
});
res.send(word);
console.log("success");
});
- 파일의 모든 정보를 읽으려면 아래이 코드를 사용하십시오.
app.get('/all',sendAll);
function sendAll(request,response){
response.send(words);
}
때 Node.js를 또는 브라우저에서 require.js를 사용하는 경우 , 당신은 간단하게 할 수 있습니다 :
let json = require('/Users/Documents/workspace/test.json');
참고 : 파일이 한 번로드되면 후속 호출에서 캐시를 사용합니다.
브라우저에 따라 로컬 파일에 액세스 할 수 있습니다. 그러나 이것은 모든 앱 사용자에게 적용되지 않을 수 있습니다.
이렇게하려면 여기에서 지침을 시도해보십시오. http://www.html5rocks.com/en/tutorials/file/dndfiles/
파일이로드되면 다음을 사용하여 데이터를 검색 할 수 있습니다.
var jsonData = JSON.parse(theTextContentOfMyFile);
Fetch API를 사용하는 것이 가장 쉬운 솔루션입니다.
fetch("test.json")
.then(response => response.json())
.then(json => console.log(json));
Firefox에서는 완벽하게 작동하지만 Chrome에서는 보안 설정을 사용자 정의해야합니다.
로컬 파일을 사용하는 경우 데이터를 js 객체로 패키징하는 것이 어떻습니까?
data.js
MyData = { resource:"A",literals:["B","C","D"]}
XMLHttpRequests , 구문 분석 없음 , MyData.resource
직접 사용하십시오.
매우 간단합니다.
json 파일의 이름을 ".json"대신 ".js"로 바꾸십시오.
<script type="text/javascript" src="my_json.js"></script>
따라서 코드를 정상적으로 따르십시오.
<script type="text/javascript">
var obj = JSON.parse(contacts);
그러나 단지 정보를 위해 내 json 콘텐츠는 아래 코드와 같습니다.
contacts='[{"name":"bla bla", "email":bla bla, "address":"bla bla"}]';
많은 사람들이 이전에 언급했듯이 AJAX 호출을 사용하면 작동하지 않습니다. 그러나 그 주위에 방법이 있습니다. 입력 요소를 사용하여 파일을 선택할 수 있습니다.
선택한 파일 (.json)은 다음 구조를 가져야합니다.
[
{"key": "value"},
{"key2": "value2"},
...
{"keyn": "valuen"},
]
<input type="file" id="get_the_file">
그런 다음 FileReader ()와 함께 JS를 사용하여 파일을 읽을 수 있습니다.
document.getElementById("get_the_file").addEventListener("change", function() {
var file_to_read = document.getElementById("get_the_file").files[0];
var fileread = new FileReader();
fileread.onload = function(e) {
var content = e.target.result;
// console.log(content);
var intern = JSON.parse(content); // Array of Objects.
console.log(intern); // You can index every object
};
fileread.readAsText(file_to_read);
});
$ .getJSON을 사용한 다음 $ .each를 사용하여 Key / value 쌍을 반복하십시오. JSON 파일 및 기능 코드의 컨텐츠 예제 :
{
{
"key": "INFO",
"value": "This is an example."
}
}
var url = "file.json";
$.getJSON(url, function (data) {
$.each(data, function (key, model) {
if (model.key == "INFO") {
console.log(model.value)
}
})
});
XMLHttpRequest () 메소드를 사용할 수 있습니다.
var xmlhttp = new XMLHttpRequest();
xmlhttp.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
var myObj = JSON.parse(this.responseText);
//console.log("Json parsed data is: " + JSON.stringify(myObj));
}
};
xmlhttp.open("GET", "your_file_name.json", true);
xmlhttp.send();
console.log 문 (commented out)을 사용하여 myObj의 응답을 볼 수 있습니다.
AngularJS를 알고 있다면 $ http를 사용할 수 있습니다.
MyController.$inject = ['myService'];
function MyController(myService){
var promise = myService.getJsonFileContents();
promise.then(function (response) {
var results = response.data;
console.log("The JSON response is: " + JSON.stringify(results));
})
.catch(function (error) {
console.log("Something went wrong.");
});
}
myService.$inject = ['$http'];
function myService($http){
var service = this;
service.getJsonFileContents = function () {
var response = $http({
method: "GET",
url: ("your_file_name.json")
});
return response;
};
}
다른 폴더에 파일이 있으면 filename 대신 전체 경로를 언급하십시오.
웹 응용 프로그램이 있으므로 클라이언트와 서버가있을 수 있습니다.
브라우저 만 있고 브라우저에서 실행중인 Javascript에서 로컬 파일을 읽으려면 클라이언트 만 있음을 의미합니다. 보안상의 이유로 브라우저는 이러한 작업을 수행하지 않아야합니다.
그러나 lauhub가 위에서 설명한 것처럼 이것은 작동하는 것 같습니다.
http://www.html5rocks.com/en/tutorials/file/dndfiles/
다른 해결책은 시스템의 어딘가에 웹 서버 (리눅스에서는 Windows 또는 원숭이에서는 거의 없음)와 XMLHttpRequest 또는 D3 라이브러리를 사용하여 서버에서 파일을 요청하고 읽는 것입니다. 서버는 로컬 파일 시스템에서 파일을 가져 와서 웹을 통해 사용자에게 제공합니다.
Stano / Meetar가 위에서 언급 한 내용이 마음에 들었습니다. .json 파일을 읽는 데 사용합니다. Promise를 사용하여 예제를 확장했습니다. 여기에 동일한 플런저가 있습니다. https://plnkr.co/edit/PaNhe1XizWZ7C0r3ZVQx?p=preview
function readTextFile(file, callback) {
var rawFile = new XMLHttpRequest();
rawFile.overrideMimeType("application/json");
rawFile.open("GET", file, true);
rawFile.onreadystatechange = function() {
if (rawFile.readyState === 4 && rawFile.status == "200") {
callback(rawFile.responseText);
}
}
rawFile.send(null);
}
//usage:
// readTextFile("DATA.json", function(text){
// var data = JSON.parse(text);
// console.log(data);
// });
var task1 = function (){
return new Promise (function(resolve, reject){
readTextFile("DATA.json", function(text){
var data = JSON.parse(text);
console.log('task1 called');
console.log(data);
resolve('task1 came back');
});
});
};
var task2 = function (){
return new Promise (function(resolve, reject){
readTextFile("DATA2.json", function(text){
var data2 = JSON.parse(text);
console.log('task2 called');
console.log(data2);
resolve('task2 came back');
});
});
}
Promise.race([task1(), task2()])
.then(function(fromResolve){
console.log(fromResolve);
});
JSON 읽기는 DRY를 위해 다른 함수로 이동할 수 있습니다. 그러나 여기 예제는 약속을 사용하는 방법을 보여줍니다.
새 XMLHttpRequest 인스턴스를 작성하고 json 파일의 컨텐츠를로드해야합니다.
이 팁은 저에게 효과적입니다 ( https://codepen.io/KryptoniteDove/post/load-json-file-locally-using-pure-javascript ) :
function loadJSON(callback) {
var xobj = new XMLHttpRequest();
xobj.overrideMimeType("application/json");
xobj.open('GET', 'my_data.json', true); // Replace 'my_data' with the path to your file
xobj.onreadystatechange = function () {
if (xobj.readyState == 4 && xobj.status == "200") {
// Required use of an anonymous callback as .open will NOT return a value but simply returns undefined in asynchronous mode
callback(xobj.responseText);
}
};
xobj.send(null);
}
loadJSON(function(response) {
// Parse JSON string into object
var actual_JSON = JSON.parse(response);
});
간단한 해결 방법 중 하나는 JSON 파일을 로컬로 실행중인 서버에 넣는 것입니다. 이를 위해 터미널에서 프로젝트 폴더로 이동하여 포트 번호 (예 : 8181)에서 로컬 서버를 시작하십시오
python -m SimpleHTTPServer 8181
그런 다음 http : // localhost : 8181 /을 탐색 하면 JSON을 포함한 모든 파일이 표시됩니다. 파이썬을 아직 설치하지 않았다면 설치하십시오.
ES6 모듈처럼 가져올 수 있습니다.
import data from "/Users/Documents/workspace/test.json"
로컬 웹 서버 ( Chris P 가 위에서 제안한대로)를 실행할 수 있고 jQuery를 사용할 수있는 경우 http://api.jquery.com/jQuery.getJSON/
data.json
다음과 같이 D3을 사용하여 콜백을 처리하고 로컬 JSON 파일을로드 할 수 있습니다 .
<script src="//d3js.org/d3.v3.min.js" charset="utf-8"></script>
<script>
d3.json("data.json", function(error, data) {
if (error)
throw error;
console.log(data);
});
</script>
나는 Stano의 훌륭한 답변을 받아 약속에 담았 습니다 . 파일 시스템에서 json 파일을로드하기 위해 대체 할 node 또는 webpack과 같은 옵션이없는 경우 유용 할 수 있습니다.
// wrapped XMLHttpRequest in a promise
const readFileP = (file, options = {method:'get'}) =>
new Promise((resolve, reject) => {
let request = new XMLHttpRequest();
request.onload = resolve;
request.onerror = reject;
request.overrideMimeType("application/json");
request.open(options.method, file, true);
request.onreadystatechange = () => {
if (request.readyState === 4 && request.status === "200") {
resolve(request.responseText);
}
};
request.send(null);
});
다음과 같이 호출 할 수 있습니다.
readFileP('<path to file>')
.then(d => {
'<do something with the response data in d.srcElement.response>'
});
따라서 JSON 파일을 호스팅하기 위해 "Apache Tomcat"을 사용하려는 경우,
1> 서버를 시작한 후 다음 URL로 이동하여 Apache Tomcat이 시작되어 실행 중인지 확인하십시오. "localhost : 8080"-
2> Next, go to the "webapps" folder - "C:\Program Files\Apache Software Foundation\Tomcat 8.5\webapps". And, create a project folder or copy your project folder.
3> Paste your json file over there.
4> And that's it. You are done! Just go to - "http://localhost:8080/$project_name$/$jsonFile_name$.json"
참고URL : https://stackoverflow.com/questions/19706046/how-to-read-an-external-local-json-file-in-javascript
'Programing' 카테고리의 다른 글
IIS7 배포- 'system.web.extensions / scripting / scriptResourceHandler'섹션 복제 (0) | 2020.05.07 |
---|---|
원래 파일로 로컬 파일을 강제로 덮어 씁니까? (0) | 2020.05.07 |
jQuery-요소가 DOM에서 제거 될 때 이벤트 트리거 (0) | 2020.05.07 |
Dapper ORM을 사용하여 ID를 입력 할 때 *에서 * 선택 (…) (0) | 2020.05.07 |
YAML에서 인디케이터 문자 (예 : 또는-)를 이스케이프 처리하는 방법 (0) | 2020.05.07 |