【问题标题】:Querying a JSON object in Node.js [closed]在 Node.js 中查询 JSON 对象 [关闭]
【发布时间】:2013-09-05 19:28:57
【问题描述】:

我对使用 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 的值。

提前感谢您的帮助

【问题讨论】:

  • 如果可能,您应该更改您的 JSON。你不需要一个里面有很多对象的数组。您只需要一个带有单独键的对象,例如 {"Accept-Charset": ["UTF-8", "ISO-8859-1"], "Accept-Encoding": ["compress", "gzip"]}...

标签: javascript json node.js npm


【解决方案1】:

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

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

【讨论】:

  • 如果 OP 想要随机访问几个键,使用 Array.prototype.reduce 过滤器将数组转换为键控对象并通过它找到它们不是更好吗代替对象?
【解决方案2】:

尽管有我的评论,我还是会像这样遍历数组:

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

【讨论】:

    猜你喜欢
    • 2016-01-26
    • 2017-12-15
    • 2016-03-26
    • 1970-01-01
    • 2020-11-05
    • 2023-01-21
    • 1970-01-01
    • 2013-03-31
    • 1970-01-01
    相关资源
    最近更新 更多