카테고리 보관물: Javascript

Javascript

로컬 JSON 파일로드 +json.responseText + “)”); document.write(data[“a”]); test.json 파일 : {“a” :

로컬 JSON 파일을로드하려고하는데 작동하지 않습니다. 다음은 jQuery를 사용하는 JavaScript 코드입니다.

var json = $.getJSON("test.json");
var data = eval("(" +json.responseText + ")");
document.write(data["a"]);

test.json 파일 :

{"a" : "b", "c" : "d"}

아무것도 표시되지 않으며 Firebug는 데이터가 정의되지 않았다고 알려줍니다. Firebug에서 볼 수 json.responseText있고 훌륭하고 유효하지만 줄을 복사하면 이상합니다.

 var data = eval("(" +json.responseText + ")");

Firebug의 콘솔에서 작동하며 데이터에 액세스 할 수 있습니다.

누구든지 해결책이 있습니까?



답변

$.getJSON 비동기식이므로 다음을 수행해야합니다.

$.getJSON("test.json", function(json) {
    console.log(json); // this will show the info it in firebug console
});


답변

angularjs 앱을 테스트하기 위해 동일한 요구가 있었고 내가 찾은 유일한 방법은 require.js를 사용하는 것입니다.

var json = require('./data.json'); //(with path)

참고 : 파일이 한 번로드되면 추가 호출에서 캐시를 사용합니다.

nodejs로 파일을 읽는 방법에 대한 자세한 내용 : http://docs.nodejitsu.com/articles/file-system/how-to-read-files-in-nodejs

require.js : http://requirejs.org/


답변

보다 현대적인 방식으로 Fetch API를 사용할 수 있습니다 .

fetch("test.json")
  .then(response => response.json())
  .then(json => console.log(json));

모든 최신 브라우저는 Fetch API를 지원합니다. (Internet Explorer는 그렇지 않지만 Edge는 그렇지 않습니다!)

출처:


답변

사용자가 파일 시스템의 어느 곳에서나 로컬 json 파일을 선택하게하려면 다음 솔루션이 작동합니다.

FileReader 및 JSON.parser를 사용하며 jquery는 사용하지 않습니다.

<html>
<body>

<form id="jsonFile" name="jsonFile" enctype="multipart/form-data" method="post">

  <fieldset>
    <h2>Json File</h2>
     <input type='file' id='fileinput'>
     <input type='button' id='btnLoad' value='Load' onclick='loadFile();'>
  </fieldset>
</form>


<script type="text/javascript">

  function loadFile() {
    var input, file, fr;

    if (typeof window.FileReader !== 'function') {
      alert("The file API isn't supported on this browser yet.");
      return;
    }

    input = document.getElementById('fileinput');
    if (!input) {
      alert("Um, couldn't find the fileinput element.");
    }
    else if (!input.files) {
      alert("This browser doesn't seem to support the `files` property of file inputs.");
    }
    else if (!input.files[0]) {
      alert("Please select a file before clicking 'Load'");
    }
    else {
      file = input.files[0];
      fr = new FileReader();
      fr.onload = receivedText;
      fr.readAsText(file);
    }

    function receivedText(e) {
      let lines = e.target.result;
      var newArr = JSON.parse(lines);
    }
  }
</script>

</body>
</html>

다음은 FileReader에 대한 좋은 소개입니다. http://www.html5rocks.com/en/tutorials/file/dndfiles/


답변

빠르고 더러운 것을 찾고 있다면 HTML 문서의 헤드에 데이터를로드하십시오.

data.js

var DATA = {"a" : "b", "c" : "d"};

index.html

<html>
<head>
   <script src="data.js" ></script>
   <script src="main.js" ></script>
</head>
...
</html>

main.js

(function(){
   console.log(DATA); // {"a" : "b", "c" : "d"}
})();

Chrome의 힙 크기는 약 4GB이므로 데이터가 더 큰 경우 다른 방법을 찾아야합니다. 다른 브라우저를 확인하려면 다음을 시도하십시오.

window.performance.memory.jsHeapSizeLimit / 1024 / 1024 / 1024 + " GBs"
// "4.046875 GBs"


답변

ES5 버전

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);
}

function init() {
    loadJSON(function(response) {
        // Parse JSON string into object
        var actual_JSON = JSON.parse(response);
    });
}

ES6 버전

const loadJSON = (callback) => {
    let 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 = () => {
        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);
}

const init = () => {
    loadJSON((response) => {
        // Parse JSON string into object
        let actual_JSON = JSON.parse(response);
    });
}


답변

Original Poster의 실제 코드 문제를 이해하거나 해결하지 않고이 질문에 몇 번이나 대답했는지 믿을 수 없습니다. 즉, 나는 초보자입니다 (2 개월의 코딩 만). 내 코드는 완벽하게 작동하지만 변경 사항을 자유롭게 제안하십시오. 해결책은 다음과 같습니다.

//include the   'async':false   parameter or the object data won't get captured when loading
var json = $.getJSON({'url': "http://spoonertuner.com/projects/test/test.json", 'async': false});

//The next line of code will filter out all the unwanted data from the object.
json = JSON.parse(json.responseText);

//You can now access the json variable's object data like this json.a and json.c
document.write(json.a);
console.log(json);

위에서 제공 한 것과 동일한 코드를 작성하는 더 짧은 방법은 다음과 같습니다.

var json = JSON.parse($.getJSON({'url': "http://spoonertuner.com/projects/test/test.json", 'async': false}).responseText);

$ .getJSON 대신 $ .ajax를 사용하여 동일한 방식으로 코드를 작성할 수도 있습니다.

var json = JSON.parse($.ajax({'url': "http://spoonertuner.com/projects/test/test.json", 'async': false}).responseText); 

마지막 으로이 작업을 수행하는 마지막 방법 은 $ .ajax를 함수로 묶는 것입니다. 나는 이것을 인정 할 수는 없지만 조금 수정했다. 나는 그것을 테스트하고 작동하며 위의 코드와 동일한 결과를 생성합니다. 이 솔루션을 여기에서 찾았습니다-> 변수에 json로드

var json = function () {
    var jsonTemp = null;
    $.ajax({
        'async': false,
        'url': "http://spoonertuner.com/projects/test/test.json",
        'success': function (data) {
            jsonTemp = data;
        }
    });
    return jsonTemp;
}();

document.write(json.a);
console.log(json);

test.json의 위 내 코드에서 볼 파일 내 서버에서 호스팅 그는 (원본 포스터)에 게시 한 것과 같은 JSON 데이터 객체를 포함합니다.

{
    "a" : "b",
    "c" : "d"
}