2013-09-02 2 views
0

나는 Node.js를 사용하는 것에있어서 아주 새로운 경험이있다. JSON 객체를 구문 분석하고 쿼리하는 좋은 방법을 찾고있었습니다. 파일로로드 된 다음 JSON 개체가 있습니다.Node.js에서 JSON 객체 쿼리하기

[ 
{"Key":"Accept","Values":["Application/x-www-form-urlencoded","Application/Json","Application/Xml"]}, 
{"Key":"Accept-Charset","Values":["UTF-8", "ISO-8859-1"]}, 
{"Key":"Accept-Encoding","Values":["compress", "gzip"]}, 
{"Key":"Accept-Language","Values":[]}, 
{"Key":"Accept-Ranges","Values":[]}, 
{"Key":"Age","Values":[]}, 
{"Key":"Allow","Values":[]}, 
{"Key":"Authorization","Values":["Bearer"]}, 
{"Key":"Cache-Control","Values":[]}, 
{"Key":"Connection","Values":[]}, 
{"Key":"Content-Encoding","Values":[]}, 
{"Key":"Content-Language","Values":[]}, 
{"Key":"Content-Length","Values":[]}, 
{"Key":"Content-Location","Values":[]}, 
{"Key":"Content-MD5","Values":[]}, 
{"Key":"Content-Range","Values":[]}, 
{"Key":"Content-Type","Values":["Application/x-www-form-urlencoded","Application/Json","Application/Xml"]}, 
{"Key":"Date","Values":[]}, 
{"Key":"ETag","Values":[]}, 
{"Key":"Expect","Values":[]}, 
{"Key":"Expires","Values":[]}, 
{"Key":"From","Values":[]}, 
{"Key":"Host","Values":[]}, 
{"Key":"If-Match","Values":[]}, 
{"Key":"If-Modified-Since","Values":[]}, 
{"Key":"If-None-Match","Values":[]}, 
{"Key":"If-Range","Values":[]}, 
{"Key":"If-Unmodified-Since","Values":[]}, 
{"Key":"Last-Modified","Values":[]}, 
{"Key":"Max-Forwards","Values":[]}, 
{"Key":"Pragma","Values":[]}, 
{"Key":"Proxy-Authenticate","Values":[]}, 
{"Key":"Proxy-Authorization","Values":[]}, 
{"Key":"Range","Values":[]}, 
{"Key":"Referer","Values":[]}, 
{"Key":"TE","Values":[]}, 
{"Key":"Trailer","Values":[]}, 
{"Key":"Transfer-Encoding","Values":[]}, 
{"Key":"Upgrade","Values":[]}, 
{"Key":"User-Agent","Values":[]}, 
{"Key":"Via","Values":[]}, 
{"Key":"Warning","Values":[]} 
] 

나는 값을 기준으로 키를 찾아 값의 배열을 반환 할 수 있어야합니다.

예를 들어, 키가 Content-Type 인 값을 찾는 방법은 무엇입니까?

+1

가능한 경우 JSON을 변경해야합니다. 배열 안에 많은 오브젝트가있는 배열이 필요하지 않습니다. '{ "Accept-Charset": [ "UTF-8", "ISO-8859-1"], "Accept-Encoding": [ "compress", "gzip"]} 같은 별도의 키를 가진 하나의 객체 만 있으면됩니다. '... – Andy

답변

2

내 의견에도 불구하고 당신의 도움에 미리

감사합니다, 정말 같은 배열을 통해 루프 것이다 : 당신은 Node.js를를 사용하고 있기 때문에

function searchByKey(key) { 
    for (var i = 0, l = arr.length; i < l; i++){ 
    if (arr[i]['Key'] === key) { 
     return arr[i]['Values']; 
    } 
    } 
    return false; 
} 
5

것은, 당신은 새로운 활용할 수 있습니다 Array.prototype.filter

var myData = require('./data.json'), 
    myFilteredData = myData.filter(function(obj) { 
    return obj.key === 'Content-Type'; 
    }); 
+0

OP가 무작위로 여러 개의 키에 액세스하려고하는 경우 Array.prototype.reduce 필터를 사용하여 배열을 키 객체로 변환하고 대신 해당 객체를 통해 찾는 것이 더 좋지 않습니까? – Spoike

관련 문제