簡體   English   中英

JSON:從對象返回整個匹配數組

[英]JSON: return whole matching array from an object

我有一個API的JSON文件。 這將為我的下一個個人網站提供靜態內容:

[
  {
    "articles": [
      {
        "_id": "0",
        "url": "audrey-hepburn",
        "title": "Audrey Hepburn",
        "category": "foo",
        "body": "Nothing is impossible, the word itself says 'I'm possible'!",
        "tags": [ "foo" ]
      },
      {
        "_id": "1",
        "url": "walt-disney",
        "title": "Walt Disney",
        "category": "foo",
        "body": "You may not realize it when it happens, but a kick in the teeth may be the best thing in the world for you.",
        "tags": [ "foo", "bar" ]
      },
      {
        "_id": "2",
        "url": "unknown",
        "title": "Unknown",
        "category": "bar",
        "body": "Even the greatest was once a beginner. Don't be afraid to take that first step.",
        "tags": [ "foo", "bar", "baz" ]
      },
      {
        "_id": "3",
        "url": "neale-donald-walsch",
        "title": "Neale Donald Walsch",
        "category": "bar",
        "body": "You are afraid to die, and you're afraid to live. What a way to exist.",
        "tags": [ "foo", "bar", "baz" ]
      },
      {
        "_id": "4",
        "url": "test",
        "title": "Test Article",
        "category": "bar",
        "body": "This is a test article.",
        "tags": [ "foo", "bar", "baz", "bam" ]
      }
    ]
  },
  {
    "users": [
      { "name": "Admin" },
      { "name": "User" }
    ]
  }
]

此JSON文件由以下API調用:

/////////////////////////////////////////////////////////////
// GRABS EVERY ARTICLES PER PAGES BY LATEST
// http://127.0.0.1:3000/api/articles/page/0/2/order/adddate/auth/<API-TOKEN>
/////////////////////////////////////////////////////////////

router.get('/articles/page/:start/:end/order/:order/auth/:token', function(req, res) {
  fsAsync(function(err, data) {
    if (err) {
      return res.send(err);
    }

    if(req.params.order === 'adddate') {
      var articles = data[0].articles.reverse();
    }
    else {
      var articles = data[0].articles;
    }

    var start = req.params.start;
    var end = req.params.end;
    var slice = articles.slice(start, end);

    var q = slice.filter(function (article) {
      return article && apiToken === req.params.token;
    });
    res.json(q);
  });
});

/////////////////////////////////////////////////////////////
// GRABS SINGLE ARTICLE BY URL
// http://127.0.0.1:3000/api/articles/url/foo/auth/<API-TOKEN>
// Match any field like "url" and not just the index "id"
/////////////////////////////////////////////////////////////

router.get('/articles/url/:id/auth/:token', function(req, res) {
  fsAsync(function(err, data) {
    if (err) {
      return res.send(err);
    }
    var articles = data[0].articles;
    var q = articles.filter(function (article) {
      // return article.id === req.params.id;
      return article.url === req.params.id && apiToken === req.params.token;
    });
    res.json(q[0]);
  });
});

單個博客文章的路由器,當我通過http://domain.com/journal/audrey-hepburn URL發出單個博客文章的請求時,它使用url API:

router.get('/:url', function(req, res, next) {
  var URL = req.params.url;
  console.log(URL);

  var reqURL = req.protocol + '://' + req.hostname + ':' + usedPort + '/api/articles/url/' + URL + '/auth/' + apiToken;

  request(reqURL, function (error, response, body) {
    console.log(JSON.parse(body));
    var articles = JSON.parse(body);
    res.render('blog-article', {
      layout: 'main',
      data: articles
    });
  })
});

單個博客文章的車把模板:

<article class="id-{{data._id}}">
  <h1><a href="/journal/{{data.url}}">{{data.title}}</a></h1>
  <div class="category"><a href="/category/{{data.category}}">{{data.category}}</a></div>
  <p>{{data.body}}</p>
  <div class="tags">
    <ul>
      {{#each data.tags}}
      <li><a href="/tags/{{this}}">{{this}}</a></li>
      {{/each}}
    </ul>
  </div>
</article>

例如,如果我想查看Audrey Hepburn嗎,請訪問我的http://domain.com/journal/audrey-hepburn URL? 我用這個解決方案。

我的問題是,如果沒有任何URL路由器解決方案,而只有第一個將每個文章數組都捕獲到JSON文件中的單個對象中的解決方案,該如何修改路由器?

當然,最簡單的方法是為每個帶有_idurl名稱的文章數組創建一個對象,但是不幸的是,我想將此模板用於帶有外部api的將來站點,而不是每個api都用唯一標識符將其發布內容分開,而不是遵循相同的路線,將請求與其他數組放在同一對象中。

謝謝您的幫助!

解決方案(謝謝您的杉杉):

var db = '/../public/articles/data.json';
var data = require(__dirname + db);

router.get('/:url', function (req, res, next) {
  var articles = data[0].articles;
  var url = req.params.url;

  var selectedArticle = articles.find(function(article) {
      return article.url === url;
  });

  console.log(selectedArticle);

  res.render('blog-article', {
    layout: 'main',
    data: selectedArticle
  });
});

您已經知道如何創建路線,只需要過濾以下文章:

router.get('/journal/:url', function (req, res, next) {
    fsAsync(function (err, data) {
        var articles = data[0].articles;
        var url = req.params.url;

        // this will get you the first article matching the url
        var selectedArticle = articles.find(function(article) {
            return article.url == url;
        });

        // render your page with selectedArticle

    });
});

附帶說明一下,如果您的JSON文件未被應用更改或不經常更改,則可以使用require一次全部加載它,而不必一次又一次地讀取文件:

// data is an object
var data = require(__dirname + db);

router.get('', function (req, res, next) {
    var articles = data[0].articles;
    // ...
});

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM