Programing

변수에 로컬 JSON 파일로드

crosscheck 2020. 10. 5. 07:37
반응형

변수에 로컬 JSON 파일로드


.json 파일을 javascript의 변수에로드하려고하는데 작동하게 할 수 없습니다. 아마도 사소한 오류 일 수 있지만 찾을 수 없습니다.

다음과 같은 정적 데이터를 사용할 때 모든 것이 잘 작동합니다.

var json = {
            id: "whatever", 
            name: "start",
            children: [{
                         "id":"0.9685","name":" contents:queue"},{
                         "id":"0.79281","name":" contents:mqq_error"}}]
        }

그래서 {}에있는 모든 것을 content.json 파일에 넣고 여기에 설명 된 것처럼 로컬 자바 스크립트 변수에로드하려고했습니다. load json into variable

var json = (function() {
        var json = null;
        $.ajax({
            'async': false,
            'global': false,
            'url': "/content.json",
            'dataType': "json",
            'success': function (data) {
                json = data;
            }
        });
        return json;
    })();

크롬 디버거로 실행했는데 항상 변수 json의 값이 null이라고 알려줍니다. content.json은이를 호출하는 .js 파일과 동일한 디렉토리에 있습니다.

내가 놓친 게 무엇입니까?


개체를 content.json에 직접 붙여 넣은 경우 잘못된 json입니다. json 키 AND 값은 값이 숫자 또는 부울이 아닌 경우 큰 따옴표 (작은 따옴표 아님)로 묶어야합니다. 아래는 유효한 json으로 객체입니다.

{
  "id": "whatever", 
  "name": "start",
  "children": [{
    "id":"0.9685","name":" contents:queue"},{
    "id":"0.79281","name":" contents:mqq_error"}]
}

(당신은 또한 여분을 가졌습니다 })


여기대답 한 내 솔루션 은 다음을 사용하는 것입니다.

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

파일은 한 번만로드되며 추가 요청은 캐시를 사용합니다.

편집 캐싱을 피하기 위해 모듈을 사용하여 주석에 제공된 이 블로그 게시물 의 도우미 기능은 다음과fs 같습니다.

var readJson = (path, cb) => {
  fs.readFile(require.resolve(path), (err, data) => {
    if (err)
      cb(err)
    else
      cb(null, JSON.parse(data))
  })
}

ES6 / ES2015의 경우 다음 과 같이 직접 가져올 수 있습니다 .

// example.json
{
    "name": "testing"
}


// ES6/ES2015
// app.js
import * as data from './example.json';
const {name} = data;
console.log(name); // output 'testing'

Typescript를 사용하는 경우 다음과 같이 json 모듈을 선언 할 수 있습니다.

// tying.d.ts
declare module "*.json" {
    const value: any;
    export default value;
}

Typescript 2.9 이상부터 추가 할 수 있습니다 -resolveJsonModule compilerOptions intsconfig.json

{
  "compilerOptions": {
    "target": "es5",
     ...
    "resolveJsonModule": true,
     ...
  },
  ...
}

두 가지 가능한 문제가 있습니다.

  1. AJAX는 비동기식이므로 json외부 함수에서 돌아 오면 정의되지 않습니다. 파일이로드되면 콜백 함수가 json어떤 값으로 설정 되지만 그 당시에는 아무도 신경 쓰지 않습니다.

    I see that you tried to fix this with 'async': false. To check whether this works, add this line to the code and check your browser's console:

    console.log(['json', json]);
    
  2. The path might be wrong. Use the same path that you used to load your script in the HTML document. So if your script is js/script.js, use js/content.json

    Some browsers can show you which URLs they tried to access and how that went (success/error codes, HTML headers, etc). Check your browser's development tools to see what happens.


The built-in node.js module fs will do it either asynchronously or synchronously depending on your needs.

You can load it using var fs = require('fs');

Asynchronous

fs.readFile('./content.json', (err, data) => {
    if (err)
      console.log(err);
    else {
      var json = JSON.parse(data);
    //your code using json object
    }
})

Synchronous

var json = JSON.parse(fs.readFileSync('./content.json').toString());

Import a JSON file with ES6:

import myJson from '/path/to/filename.json'
myJsonString = JSON.stringify(myJson)

If the file is in the same directory, you can use

import myJson from './filename.json

Before ES6

var json = require('./filename.json');

참고URL : https://stackoverflow.com/questions/14484613/load-local-json-file-into-variable

반응형