[javascript] Node.js의 JSON 객체로 응답 (객체 / 배열을 JSON 문자열로 변환)

저는 백엔드 코드에 대한 초보자이고 JSON 문자열에 응답하는 함수를 만들려고합니다. 나는 현재 예제에서 이것을 가지고 있습니다.

function random(response) {
  console.log("Request handler 'random was called.");
  response.writeHead(200, {"Content-Type": "text/html"});

  response.write("random numbers that should come in the form of json");
  response.end();
}

이것은 기본적으로 “JSON 형식으로 제공되어야하는 임의의 숫자”문자열을 인쇄합니다. 내가 원하는 것은 숫자에 관계없이 JSON 문자열로 응답하는 것입니다. 다른 콘텐츠 유형을 입력해야합니까? 이 함수는 그 값을 클라이언트 측에서 말하는 다른 사람에게 전달해야합니까?

당신의 도움을 주셔서 감사합니다!



답변

Express와 함께 res.json 사용 :

function random(response) {
  console.log("response.json sets the appropriate header and performs JSON.stringify");
  response.json({
    anObject: { item1: "item1val", item2: "item2val" },
    anArray: ["item1", "item2"],
    another: "item"
  });
}

또는 :

function random(response) {
  console.log("Request handler random was called.");
  response.writeHead(200, {"Content-Type": "application/json"});
  var otherArray = ["item1", "item2"];
  var otherObject = { item1: "item1val", item2: "item2val" };
  var json = JSON.stringify({
    anObject: otherObject,
    anArray: otherArray,
    another: "item"
  });
  response.end(json);
}


답변

var objToJson = { };
objToJson.response = response;
response.write(JSON.stringify(objToJson));

당신이 경우 alert(JSON.stringify(objToJson))당신은 얻을 것이다{"response":"value"}


답변

JSON.stringify()노드가 사용하는 V8 엔진에 포함 된 기능 을 사용해야 합니다.

var objToJson = { ... };
response.write(JSON.stringify(objToJson));

편집 : 내가 아는 한, IANARFC4627application/json 에서 와 같이 JSON에 대한 MIME 유형을 공식적으로 등록했습니다 . 여기에있는 인터넷 미디어 유형 목록에도 나열 됩니다 .


답변

JamieL대답또 다른 포스트 :

Express.js 3x 이후 응답 객체에는 모든 헤더를 올바르게 설정하는 json () 메서드가 있습니다.

예:

res.json({"foo": "bar"});

답변

익스프레스에는 애플리케이션 범위의 JSON 포맷터가있을 수 있습니다.

express \ lib \ response.js를 살펴본 후 다음 루틴을 사용하고 있습니다.

function writeJsonPToRes(app, req, res, obj) {
    var replacer = app.get('json replacer');
    var spaces = app.get('json spaces');
    res.set('Content-Type', 'application/json');
    var partOfResponse = JSON.stringify(obj, replacer, spaces)
        .replace(/\u2028/g, '\\u2028')
        .replace(/\u2029/g, '\\u2029');
    var callback = req.query[app.get('jsonp callback name')];
    if (callback) {
        if (Array.isArray(callback)) callback = callback[0];
        res.set('Content-Type', 'text/javascript');
        var cb = callback.replace(/[^\[\]\w$.]/g, '');
        partOfResponse = 'typeof ' + cb + ' === \'function\' && ' + cb + '(' + partOfResponse + ');\n';
    }
    res.write(partOfResponse);
}


답변

const http = require('http');
const url = require('url');

http.createServer((req,res)=>{

    const parseObj =  url.parse(req.url,true);
    const users = [{id:1,name:'soura'},{id:2,name:'soumya'}]

    if(parseObj.pathname == '/user-details' && req.method == "GET") {
        let Id = parseObj.query.id;
        let user_details = {};
        users.forEach((data,index)=>{
            if(data.id == Id){
                user_details = data;
            }
        })
        res.writeHead(200,{'x-auth-token':'Auth Token'})
        res.write(JSON.stringify(user_details)) // Json to String Convert
        res.end();
    }
}).listen(8000);

기존 프로젝트에서 위의 코드를 사용했습니다.


답변