JSON을 로컬 텍스트 파일에 저장하는 방법


84

다음과 같은 javascript 객체가 있다고 가정합니다.

  var data = {
      name: "cliff",
      age: "34",
      name: "ted",
      age: "42",
      name: "bob",
      age: "12"
    }

var jsonData = JSON.stringify(data);

JSON으로 변환하기 위해 문자열 화합니다. 이 JSON을 메모장 등에서 열 수 있도록 로컬 텍스트 파일에 저장하려면 어떻게해야합니까?

답변:


184

Node.js :

var fs = require('fs');
fs.writeFile("test.txt", jsonData, function(err) {
    if (err) {
        console.log(err);
    }
});

브라우저 (webapi) :

function download(content, fileName, contentType) {
    var a = document.createElement("a");
    var file = new Blob([content], {type: contentType});
    a.href = URL.createObjectURL(file);
    a.download = fileName;
    a.click();
}
download(jsonData, 'json.txt', 'text/plain');

3
여기에 제시된 것처럼 가능합니다, 당신은 단지, 유형 = 파일을 사용하여 입력 태그에 있습니다 stackoverflow.com/questions/13709482/...
라팔 Łużyński

11
내가 얻을 [object Object]나는이 작업을 수행 할 때

37
@JackNicholson 나도 방금 [object Object].. 객체 자체보다 JSON.stringify()먼저 호출 하고 해당 값을 전달 해야 했습니다.
ne1410s

1
그것은 나를 위해 일했지만 파일을 바꾸지 않고 파일에 텍스트를 추가하고 싶지 않으면 어떻게됩니까?
Cesar Leonardo Ochoa Contreras

4
이후 a.click()revokeObjectURL파일에 대한 참조를 더 이상 유지하지 않도록 브라우저에 알리기 위해 호출해야합니다 . URL.revokeObjectURL(a.href).추가 정보 : developer.mozilla.org/en-US/docs/Web/API/URL/revokeObjectURL .
andreivictor 19

8

다음은 순수한 js에 대한 해결책입니다. html5 saveAs로 할 수 있습니다. 예를 들어이 lib가 도움이 될 수 있습니다. https://github.com/eligrey/FileSaver.js
데모를보십시오 : http://eligrey.com/demos/FileSaver.js/
PS json 저장에 대한 정보는 없지만 파일 유형을 변경 "application/json"하고 형식을.json


"application / json"및 .json은 html 파일 시스템에서 잘 작동합니다. 또한 이것을 사용하여 "Unexpected token? in JSON"과 같은 json 구문 분석 오류를 방지합니다. 감사.
Ajay Singh

5

로컬 데이터를 txt 파일에 저장하는 것이 내 솔루션입니다.

function export2txt() {
  const originalData = {
    members: [{
        name: "cliff",
        age: "34"
      },
      {
        name: "ted",
        age: "42"
      },
      {
        name: "bob",
        age: "12"
      }
    ]
  };

  const a = document.createElement("a");
  a.href = URL.createObjectURL(new Blob([JSON.stringify(originalData, null, 2)], {
    type: "text/plain"
  }));
  a.setAttribute("download", "data.txt");
  document.body.appendChild(a);
  a.click();
  document.body.removeChild(a);
}
<button onclick="export2txt()">Export data to local txt file</button>

당사 사이트를 사용함과 동시에 당사의 쿠키 정책개인정보 보호정책을 읽고 이해하였음을 인정하는 것으로 간주합니다.
Licensed under cc by-sa 3.0 with attribution required.