react js의 로컬 JSON 파일을 분석하려면 어떻게 해야 하는가?
JSON 파일을 통해 데이터를 모두 검색하여 코드에 사용하는 방법은?
파일 가져오기를 시도하고 콘솔 로깅을 시도했지만 개체 {} 인쇄만 수행됨:
import jsonData from "./file.json";
console.log(jsonData);
내 file.json은 다음과 같이 보인다.
[
{
"id": 1,
"gender": "Female",
"first_name": "Helen",
"last_name": "Nguyen",
"email": "hnguyen0@bloomberg.com",
"ip_address": "227.211.25.18"
}, {
"id": 2,
"gender": "Male",
"first_name": "Carlos",
"last_name": "Fowler",
"email": "cfowler1@gnu.org",
"ip_address": "214.248.201.11"
}
]
각 구성 요소의 이름과 성을 액세스하여 웹사이트에 인쇄할 수 있었으면 좋겠어.
var data = require('../../file.json'); // forward slashes will depend on the file location
var data = [
{
"id": 1,
"gender": "Female",
"first_name": "Helen",
"last_name": "Nguyen",
"email": "hnguyen0@bloomberg.com",
"ip_address": "227.211.25.18"
}, {
"id": 2,
"gender": "Male",
"first_name": "Carlos",
"last_name": "Fowler",
"email": "cfowler1@gnu.org",
"ip_address": "214.248.201.11"
}
];
for (var i = 0; i < data.length; i++)
{
var obj = data[i];
console.log(`Name: ${obj.last_name}, ${obj.first_name}`);
}
https://jsfiddle.net/c9wupvo6/
나는 또한 빈 오브젝트를 되찾는 데 문제가 있었다.사용 시에도require
상술한 바와 같이
fetch
하지만 내 문제를 해결했다.
fetch('./data/fakeData.json')
.then((res) => res.json())
.then((data) => {
console.log('data:', data);
})
(오늘부로, 지원이 최적이지는 않지만: http://caniuse.com/#feat=fetch)
웹 팩 2.0.0+로 패키지된 애플리케이션(예: create-react-app으로 작성된 애플리케이션)은 질문 내용과 동일하게 json에서 가져오기를 지원한다(이 답변 참조).
에 유의하십시오.import
결과를 캐시한다. 그 결과가 파싱된 json이더라도, 그래서 만약 당신이 그 개체를 수정한다면, 그것 또한 가져오는 다른 모듈들은 새로 파싱된 복사본이 아닌 동일한 객체에 대한 참조를 가지고 있다.
"깨끗한" 복사본을 얻으려면 다음과 같이 복제하는 기능을 만들 수 있다.
import jsonData from './file.json';
const loadData = () => JSON.parse(JSON.stringify(jsonData));
또는 lodash를 사용하는 경우:
import jsonData from './file.json';
import { cloneDeep } from 'lodash';
const loadData = () => cloneDeep(jsonData);
이것 역시 문제가 있는 분들에게는 이 코드가 문제를 고친 것 같았다.
var jsonData = require('../../file.json');
class blah extends React.Component {
render(){
var data;
function loadJSON(jsonfile, callback) {
var jsonObj = new XMLHttpRequest();
jsonObj.overrideMimeType("application/json");
jsonObj.open('GET', "../../file.json", true);
jsonObj.onreadystatechange = function () {
if (jsonObj.readyState == 4 && jsonObj.status == "200") {
callback(jsonObj.responseText);
}
};
jsonObj.send(null);
}
function load() {
loadJSON(jsonData, function(response) {
data = JSON.parse(response);
console.log(data);
});
}
load();
}
}
JS 스프레드 운영자는 또한 그 물체의 깊은 복사본을 얻는 것을 돕는다.
import jsonData from '../../file.json';
const loadData = [...jsonData];
참조URL: https://stackoverflow.com/questions/37649695/how-can-i-parse-through-local-json-file-in-react-js
'programing' 카테고리의 다른 글
Python 3에서 웹에서 파일 다운로드 (0) | 2022.03.14 |
---|---|
Firebase 함수 다시 쓰기 및 vue 라우터와의 충돌 (0) | 2022.03.13 |
Python 3에서 "100000000000000000000001"이 왜 그렇게 빠른가? (0) | 2022.03.13 |
VueJS 조건부로 요소의 속성 추가 (0) | 2022.03.13 |
CDN 링크를 사용하여 라이브러리를 reactj로 가져오는 방법 (0) | 2022.03.13 |