Node.js를 사용하여 JSON을 구문 분석하는 방법은 무엇입니까?
Node.js를 사용하여 JSON을 어떻게 구문 분석해야합니까? JSON을 안전하게 검증하고 구문 분석하는 모듈이 있습니까?
간단히 사용할 수 있습니다 JSON.parse
.
JSON
객체 의 정의 는 ECMAScript 5 사양의 일부입니다 . node.js는 ECMA 표준을 준수하는 Google Chrome의 V8 엔진을 기반으로합니다. 따라서 node.js에는 전역 개체 [docs]도 있습니다.JSON
주- JSON.parse
동기식 메소드이기 때문에 현재 스레드를 묶을 수 있습니다. 따라서 큰 JSON 객체를 파싱 할 계획이라면 스트리밍 json 파서를 사용하십시오.
.json 파일 이 필요할 수 있습니다.
var parsedJSON = require('./file-name');
예를 들어 config.json
소스 코드 파일과 동일한 디렉토리에 파일 이있는 경우 다음을 사용합니다.
var config = require('./config.json');
또는 (파일 확장자는 생략 가능) :
var config = require('./config');
참고 require
인 동기 만 파일을 읽고 한 번은 , 다음의 호출은 캐시에서 결과를 반환
또한 파일 내의 모든 코드를 잠재적으로 실행하므로 절대적으로 제어 할 수있는 로컬 파일에만 이것을 사용해야합니다.
사용할 수 있습니다JSON.parse()
.
ECMAScript 5 호환 JavaScript 구현 에서 JSON
객체 를 사용할 수 있어야합니다 . 그리고 Node.js가 구축 된 V8도 그중 하나입니다.
참고 : JSON 파일을 사용하여 민감한 정보 (예 : 암호)를 저장하는 경우 잘못된 방법입니다. Heroku가 어떻게 수행하는지 확인하십시오 : https://devcenter.heroku.com/articles/config-vars#setting-up-config-vars-for-a-deployed-application . 플랫폼이 어떻게 작동하는지 알아보고
process.env
코드 내에서 구성 변수를 검색하는 데 사용 합니다.
JSON 데이터가 포함 된 문자열 구문 분석
var str = '{ "name": "John Doe", "age": 42 }';
var obj = JSON.parse(str);
JSON 데이터가 포함 된 파일 구문 분석
fs
모듈로 몇 가지 파일 작업을 수행해야 합니다.
비동기 버전
var fs = require('fs');
fs.readFile('/path/to/file.json', 'utf8', function (err, data) {
if (err) throw err; // we'll not consider error handling for now
var obj = JSON.parse(data);
});
동기 버전
var fs = require('fs');
var json = JSON.parse(fs.readFileSync('/path/to/file.json', 'utf8'));
사용 require
하시겠습니까? 다시 생각 해봐!
var obj = require('path/to/file.json');
그러나 몇 가지 이유로 이것을 권장하지 않습니다.
require
동기식입니다. 매우 큰 JSON 파일이 있으면 이벤트 루프가 막힐 것입니다. 당신은 정말 사용할 필요JSON.parse
로fs.readFile
.require
파일을 한 번만 읽습니다 .require
동일한 파일 에 대한 후속 호출 은 캐시 된 복사본을 반환합니다..json
지속적으로 업데이트 되는 파일 을 읽으려는 경우 좋지 않습니다. 해킹을 사용할 수 있습니다 . 그러나이 시점에서는 단순히를 사용하는 것이 더 쉽습니다fs
.- 파일에
.json
확장자 가없는 경우 파일require
의 내용을 JSON으로 처리하지 않습니다.
진지하게! 사용JSON.parse
.
load-json-file
기준 치수
많은 수의 .json
파일을 읽는 경우 (그리고 매우 게으른 경우) 매번 상용구 코드를 작성하는 것이 성가 시게됩니다. load-json-file
모듈 을 사용하여 일부 문자를 저장할 수 있습니다 .
const loadJsonFile = require('load-json-file');
비동기 버전
loadJsonFile('/path/to/file.json').then(json => {
// `json` contains the parsed object
});
동기 버전
let obj = loadJsonFile.sync('/path/to/file.json');
스트림에서 JSON 구문 분석
JSON 콘텐츠가 네트워크를 통해 스트리밍되는 경우 스트리밍 JSON 파서를 사용해야합니다. 그렇지 않으면 프로세서를 묶고 JSON 콘텐츠가 완전히 스트리밍 될 때까지 이벤트 루프를 막습니다.
있다 NPM에서 사용할 수있는 패키지의 많은 이에 대한이. 자신에게 가장 적합한 것을 선택하십시오.
오류 처리 / 보안
전달 된 JSON.parse()
것이 유효한 JSON 인지 확실하지 않은 경우 블록 JSON.parse()
내부에 호출을 포함해야합니다 try/catch
. 사용자가 제공 한 JSON 문자열은 애플리케이션을 충돌시킬 수 있으며 보안 허점으로 이어질 수도 있습니다. 외부에서 제공 한 JSON을 구문 분석하는 경우 오류 처리가 완료되었는지 확인하십시오.
사용 JSON 개체를 :
JSON.parse(str);
JSON.parse의 또 다른 예 :
var fs = require('fs');
var file = __dirname + '/config.json';
fs.readFile(file, 'utf8', function (err, data) {
if (err) {
console.log('Error: ' + err);
return;
}
data = JSON.parse(data);
console.dir(data);
});
전역 JSON 객체에 대한 대안이 있음을 언급하고 싶습니다. JSON.parse
그리고 JSON.stringify
당신이 비동기 JSON 모듈의 일부를 체크 아웃 할 수있는 큰 개체를 처리 할 그렇다면, 동기식입니다.
보세요 : https://github.com/joyent/node/wiki/Modules#wiki-parsers-json
node-fs
도서관을 포함하십시오 .
var fs = require("fs");
var file = JSON.parse(fs.readFileSync("./PATH/data.json", "utf8"));
'fs'라이브러리에 대한 자세한 정보는 http://nodejs.org/api/fs.html 의 문서를 참조하십시오.
문자열이 실제로 유효한지 모르기 때문에 먼저 try catch에 넣을 것입니다. 또한 try catch 블록은 노드에 의해 최적화되지 않기 때문에 전체를 다른 함수에 넣을 것입니다.
function tryParseJson(str) {
try {
return JSON.parse(str);
} catch (ex) {
return null;
}
}
또는 "비동기 스타일"
function tryParseJson(str, callback) {
process.nextTick(function () {
try {
callback(null, JSON.parse(str));
} catch (ex) {
callback(ex)
}
})
}
JSON 스트림 구문 분석? 사용 JSONStream
.
var request = require('request')
, JSONStream = require('JSONStream')
request({url: 'http://isaacs.couchone.com/registry/_all_docs'})
.pipe(JSONStream.parse('rows.*'))
.pipe(es.mapSync(function (data) {
return data
}))
https://github.com/dominictarr/JSONStream
여기있는 모든 사람들이 JSON.parse에 대해 말 했으므로 다른 말을 생각했습니다. 많은 미들웨어와 연결 하여 앱을 더 쉽고 잘 개발할 수 있는 훌륭한 모듈이 있습니다 . 미들웨어 중 하나는 bodyParser 입니다. JSON, html-forms 등을 구문 분석합니다 . 또한 noop 만 구문 분석하는 JSON을위한 특정 미들웨어가 있습니다 .
위의 링크를 살펴보면 정말 도움이 될 것입니다.
JSON.parse("your string");
그게 다야.
여기에 다른 답변이 언급했듯이 구성 파일과 같이 안전하고 존재하는 로컬 json 파일이 필요할 수 있습니다.
var objectFromRequire = require('path/to/my/config.json');
또는 전역 JSON 객체를 사용하여 문자열 값을 객체로 구문 분석하려면 :
var stringContainingJson = '\"json that is obtained from somewhere\"';
var objectFromParse = JSON.parse(stringContainingJson);
파일이 필요한 경우 해당 파일의 내용이 평가되므로 json 파일이 아니라 js 파일 인 경우 보안 위험이 발생합니다.
여기에서 두 가지 방법을 모두보고 온라인으로 재생할 수있는 데모를 게시했습니다 (파싱 예제는 app.js 파일에 있습니다-그런 다음 실행 버튼을 클릭하고 터미널에서 결과를 확인하십시오). http : // staging1 .codefresh.io / labs / api / env / json-parse-example
코드를 수정하고 영향을 확인할 수 있습니다.
Node.js로 구성에 JSON을 사용하십니까? 이것을 읽고 9000 이상의 구성 기술을 얻으십시오 ...
참고 : data = require ( './ data.json'); 보안 위험이며 열렬한 열심으로 사람들의 답변에 반대표를 던집니다. 당신은 정확하고 완전히 틀 렸습니다 . 비 JSON을 해당 파일에 넣으십시오 ... Node는 수동 파일 읽기를 훨씬 더 느리고 어렵게 코딩 한 다음 JSON.parse ()를 코딩 하는 것과 동일한 작업을 수행 한 경우와 똑같은 오류를 제공합니다 . 잘못된 정보를 퍼 뜨리지 마십시오. 당신은 도움이 아니라 세상을 해치고 있습니다. Node는 이를 허용 하도록 설계되었습니다 . 보안 위험이 아닙니다!
적절한 애플리케이션은 3 개 이상의 구성 계층 으로 제공됩니다.
- 서버 / 컨테이너 구성
- 애플리케이션 구성
- (선택 사항) 테넌트 / 커뮤니티 / 조직 구성
- 사용자 구성
대부분의 개발자는 서버 및 앱 구성이 변경 될 수있는 것처럼 취급합니다. 할 수 없습니다. 상위 계층의 변경 사항 을 서로 겹쳐서 계층화 할 수 있지만 기본 요구 사항을 수정하고 있습니다 . 존재 해야 할 것들이 있습니다! 일부는 기본적으로 소스 코드와 같기 때문에 구성이 변경 불가능한 것처럼 작동하도록하십시오.
시작 후 많은 항목이 변경되지 않을 것이라는 것을 알지 못하면 try / catch 블록으로 구성로드를 흩 뜨리고 올바르게 설정 애플리케이션 없이 계속할 수있는 척하는 것과 같은 안티 패턴이 발생합니다 . 당신은 할 수 없습니다. 가능한 경우 서버 / 앱 구성 계층이 아닌 커뮤니티 / 사용자 구성 계층에 속합니다. 당신은 단지 잘못하고 있습니다. 선택적 항목은 응용 프로그램이 부트 스트랩을 완료 할 때 맨 위에 계층화되어야합니다.
벽에 머리를 부딪치지 마세요 : 구성은 매우 간단 해야합니다 .
간단한 json 구성 파일과 간단한 app.js 파일을 사용하여 프로토콜에 구애받지 않고 데이터 소스에 구애받지 않는 서비스 프레임 워크와 같이 복잡한 것을 설정하는 것이 얼마나 쉬운 지 살펴보십시오.
container-config.js ...
{
"service": {
"type" : "http",
"name" : "login",
"port" : 8085
},
"data": {
"type" : "mysql",
"host" : "localhost",
"user" : "notRoot",
"pass" : "oober1337",
"name" : "connect"
}
}
index.js ... (모든 것을 구동하는 엔진)
var config = require('./container-config.json'); // Get our service configuration.
var data = require(config.data.type); // Load our data source plugin ('npm install mysql' for mysql).
var service = require(config.service.type); // Load our service plugin ('http' is built-in to node).
var processor = require('./app.js'); // Load our processor (the code you write).
var connection = data.createConnection({ host: config.data.host, user: config.data.user, password: config.data.pass, database: config.data.name });
var server = service.createServer(processor);
connection.connect();
server.listen(config.service.port, function() { console.log("%s service listening on port %s", config.service.type, config.service.port); });
app.js ... (프로토콜 불가지론 및 데이터 소스 불가지론 서비스를 지원하는 코드)
module.exports = function(request, response){
response.end('Responding to: ' + request.url);
}
이 패턴을 사용하면 이제 부팅 된 앱 위에 커뮤니티 및 사용자 구성 항목을로드 할 수 있습니다. dev ops는 작업을 컨테이너에 넣고 확장 할 준비가되었습니다. 다중 테넌트에 대해 읽었습니다. Userland는 격리되어 있습니다. 이제 사용중인 서비스 프로토콜, 사용중인 데이터베이스 유형에 대한 문제를 분리하고 좋은 코드 작성에만 집중할 수 있습니다.
당신이 레이어를 사용하기 때문에, 당신은 젠장, 내가 어떻게 만들려고하고있다 "걱정, 언제든지 (계층화 설정 개체)에서, 모두를위한 진리의 단일 소스에 의존하고, 모든 단계에서 피할 오류를 검사 할 수 이 적절한 구성없이 작동합니까?!? ".
내 솔루션 :
var fs = require('fs');
var file = __dirname + '/config.json';
fs.readFile(file, 'utf8', function (err, data) {
if (err) {
console.log('Error: ' + err);
return;
}
data = JSON.parse(data);
console.dir(data);
});
답변을 완료하고 (한동안 고생하면서) json 정보에 액세스하는 방법을 보여주고 싶습니다.이 예제는 Json Array에 액세스하는 방법을 보여줍니다.
var request = require('request');
request('https://server/run?oper=get_groups_joined_by_user_id&user_id=5111298845048832', function (error, response, body) {
if (!error && response.statusCode == 200) {
var jsonArr = JSON.parse(body);
console.log(jsonArr);
console.log("group id:" + jsonArr[0].id);
}
})
가능한 한 복잡하게 만들고 가능한 한 많은 패키지를 가져 오십시오.
const fs = require('fs');
const bluebird = require('bluebird');
const _ = require('lodash');
const readTextFile = _.partial(bluebird.promisify(fs.readFile), _, {encoding:'utf8',flag:'r'});
const readJsonFile = filename => readTextFile(filename).then(JSON.parse);
이를 통해 다음을 수행 할 수 있습니다.
var dataPromise = readJsonFile("foo.json");
dataPromise.then(console.log);
또는 async / await를 사용하는 경우 :
let data = await readJsonFile("foo.json");
그냥 사용하는 것보다 장점 readFileSync
은 파일이 디스크에서 읽히는 동안 노드 서버가 다른 요청을 처리 할 수 있다는 것입니다.
JSON.parse는 구문 분석중인 json 문자열의 안전성을 보장하지 않습니다. json-safe-parse 또는 유사한 라이브러리 와 같은 라이브러리를 살펴보아야 합니다.
json-safe-parse npm 페이지에서 :
JSON.parse는 훌륭하지만 JavaScript의 맥락에서 심각한 결함이 하나 있습니다. 상속 된 속성을 재정의 할 수 있습니다. 신뢰할 수없는 소스 (예 : 사용자)에서 JSON을 구문 분석하고 존재할 것으로 예상되는 함수를 호출하는 경우 문제가 될 수 있습니다.
Lodash의 시도 함수를 활용하여 isError 함수로 처리 할 수있는 오류 객체를 반환합니다.
// Returns an error object on failure
function parseJSON(jsonString) {
return _.attempt(JSON.parse.bind(null, jsonString));
}
// Example Usage
var goodJson = '{"id":123}';
var badJson = '{id:123}';
var goodResult = parseJSON(goodJson);
var badResult = parseJSON(badJson);
if (_.isError(goodResult)) {
console.log('goodResult: handle error');
} else {
console.log('goodResult: continue processing');
}
// > goodResult: continue processing
if (_.isError(badResult)) {
console.log('badResult: handle error');
} else {
console.log('badResult: continue processing');
}
// > badResult: handle error
json에 손상된 데이터가있는 경우 노드가 항상 예기치 않은 오류를 발생 시키므로 try catch 블록 에서 JSON.parse를 사용하십시오. 간단한 JSON 대신이 코드를 사용하십시오.
try{
JSON.parse(data)
}
catch(e){
throw new Error("data is corrupted")
}
JSON에 주석을 추가하고 후행 쉼표를 허용하려면 아래 구현을 사용할 수 있습니다.
var fs = require('fs');
var data = parseJsData('./message.json');
console.log('[INFO] data:', data);
function parseJsData(filename) {
var json = fs.readFileSync(filename, 'utf8')
.replace(/\s*\/\/.+/g, '')
.replace(/,(\s*\})/g, '}')
;
return JSON.parse(json);
}
"abc": "foo // bar"
JSON 과 같은 것이 있으면 제대로 작동하지 않을 수 있습니다 . 그래서 YMMV.
If the JSON source file is pretty big, may want to consider the asynchronous route via native async / await approach with Node.js 8.0 as follows
const fs = require('fs')
const fsReadFile = (fileName) => {
fileName = `${__dirname}/${fileName}`
return new Promise((resolve, reject) => {
fs.readFile(fileName, 'utf8', (error, data) => {
if (!error && data) {
resolve(data)
} else {
reject(error);
}
});
})
}
async function parseJSON(fileName) {
try {
return JSON.parse(await fsReadFile(fileName));
} catch (err) {
return { Error: `Something has gone wrong: ${err}` };
}
}
parseJSON('veryBigFile.json')
.then(res => console.log(res))
.catch(err => console.log(err))
I use fs-extra. I like it a lot because -although it supports callbacks- it also supports Promises. So it just enables me to write my code in a much more readable way:
const fs = require('fs-extra');
fs.readJson("path/to/foo.json").then(obj => {
//Do dome stuff with obj
})
.catch(err => {
console.error(err);
});
It also has many useful methods which do not come along with the standard fs
module and, on top of that, it also bridges the methods from the native fs
module and promisifies them.
NOTE: You can still use the native Node.js methods. They are promisified and copied over to fs-extra. See notes on
fs.read()
&fs.write()
So it's basically all advantages. I hope others find this useful.
You can use JSON.parse() (which is a built in function that will probably force you to wrap it with try-catch statements).
Or use some JSON parsing npm library, something like json-parse-or
Use JSON.parse(str);
. Read more it here.
Here are some examples:
var jsonStr = '{"result":true, "count":42}';
obj = JSON.parse(jsonStr);
console.log(obj.count); //expected output: 42
console.log(obj.result); // expected output: true
Use this to be on the safe side
var data = JSON.parse(Buffer.concat(arr).toString());
NodeJs is a JavaScript based server, so you can do the way you do that in pure JavaScript...
Imagine you have this Json in NodeJs...
var details = '{ "name": "Alireza Dezfoolian", "netWorth": "$0" }';
var obj = JSON.parse(details);
And you can do above to get a parsed version of your json...
As mentioned in the above answers, We can use JSON.parse()
to parse the strings to JSON But before parsing, be sure to parse the correct data or else it might bring your whole application down
it is safe to use it like this
let parsedObj = {}
try {
parsedObj = JSON.parse(data);
} catch(e) {
console.log("Cannot parse because data is not is proper json format")
}
No further modules need to be required.
Just use
var parsedObj = JSON.parse(yourObj);
I don think there is any security issues regarding this
It's simple, you can convert JSON to string using JSON.stringify(json_obj)
, and convert string to JSON using JSON.parse("your json string")
.
var fs = require('fs');
fs.readFile('ashish.json',{encoding:'utf8'},function(data,err) {
if(err)
throw err;
else {
console.log(data.toString());
}
})
참고URL : https://stackoverflow.com/questions/5726729/how-to-parse-json-using-node-js
'program tip' 카테고리의 다른 글
RecyclerView에 onItemClickListener ()가없는 이유는 무엇입니까? (0) | 2020.09.28 |
---|---|
로컬 디렉터리에서 requirements.txt 파일에 따라 pip를 사용하여 패키지를 설치하는 방법은 무엇입니까? (0) | 2020.09.28 |
사용자가 외부를 클릭 할 때 jQuery를 사용하여 DIV를 숨 깁니다. (0) | 2020.09.28 |
Ubuntu의 Apache 서버 벤치마킹 도구 AB를 포함하는 패키지는 무엇입니까? (0) | 2020.09.25 |
C libcurl은 출력을 문자열로 가져옵니다. (0) | 2020.09.25 |