【问题标题】:How to reference a specific item in a json data set?如何引用 json 数据集中的特定项目?
【发布时间】:2018-11-15 22:33:28
【问题描述】:

我正在使用 NewsApi 将一些数据提取到我的新闻模型中。请求是RestClient.get(https://newsapi.org/v2/top-headlines?sources=financial-times&apiKey=XXXXX) { |response| },它返回一个我解析为json的数据集:

data = JSON.parse(response.body)

=>

{
"status": "ok",
"totalResults": 10,
-"articles": [
-{
-"source": {
"id": ".....",
"name": "....."
},
"author": null,
"title": "......",
"description": "......",
"url": "......",
"urlToImage": "....."
},
-{
-"source": {
"id": "financial-times",
"name": "Financial Times"
},
"author": null,
"title": "...",
"description": "...",
"url": "https://www.ft.com/content/a6a3cb08-e887-11e8-8a85-04b8afea6ea3",
"urlToImage":"..."
}
]
}

我想知道如何检索每篇文章中"title" 元素的值。 @news.title = data["articles"][1]["title"] 等等... 在任何文章中具体引用 "title" 元素的最快方法是什么?

【问题讨论】:

    标签: ruby-on-rails arrays json ruby-on-rails-5


    【解决方案1】:

    我不是 100% 清楚你到底想要什么,但如果你只想要数组中每篇文章的标题值,你可以这样做:

    data[:articles].map { |a| a[:title] }

    这将输出标题数组=> ["......", "..."]

    如果您只想在文章数组中引用特定文章的标题,那么您已经得到了它 - data[:articles][X][:title],其中 X 是特定文章的索引。

    【讨论】:

    • 谢谢。只需将 json 名称的语法调整为 data["articles"].map 等。这样就完美了。
    猜你喜欢
    • 1970-01-01
    • 2019-10-01
    • 2011-09-14
    • 2014-09-05
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-11-06
    相关资源
    最近更新 更多