在Node.js中查询JSON对象

时间:2013-09-02 16:28:57

标签: javascript json node.js npm

我很擅长使用Node.js.我一直在寻找一种解析和查询JSON对象的好方法。我将以下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":[]}
]

我希望能够按值找到Key并返回values数组。

例如,我如何找到密钥等于Content-Type的值。

提前感谢您的帮助

2 个答案:

答案 0 :(得分:6)

由于您使用的是Node.js,因此您可以利用较新的Array.prototype.filter

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

答案 1 :(得分:1)

尽管我的评论,我会像这样循环遍历数组:

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