【问题标题】:Searching (filtering) JSON array with 'key == value' condition使用“key == value”条件搜索(过滤)JSON 数组
【发布时间】:2019-01-08 13:20:08
【问题描述】:

我在 ruby​​ 中搜索数组中的特定对象时遇到问题。

我已向https://jsonplaceholder.typicode.com/todos 发出请求,从那里我得到结果 JSON。我正在尝试将其转换为对象数组,然后搜索事件(我知道我可以使用参数发出请求,它会解决我的问题,但我无权访问后端)。

我试图在包含某些(特定)值的数组中打印对象,并获取布尔值来说明该字符串是否存在于数组中(我还试图在堆栈上找到我的问题的答案(这个似乎是最接近我的问题Ruby find and return objects in an array based on an attribute 但对我帮助不大)。

client = HTTPClient.new
method = 'GET'
url = URI.parse 'https://jsonplaceholder.typicode.com/todos'
res = client.request method, url
dd = JSON.parse(res.body)
puts dd.select { |word| word.completed == false }
puts dd.include?('temporibus atque distinctio omnis eius impedit tempore molestias pariatur')

实际结果

include? 返回的selectfalse 根本没有结果

预期结果

select 应该放在终端对象上,completed 等于 false;

如果数组中存在作为参数提供的值,include? 应该返回 true

【问题讨论】:

  • 在您的 typicode 链接中,所有 title 条目都缺少行尾的逗号 { "UserId": 1, "Id": 1, "Title": "selected either the" "Completed" false @987654338 @ 如果它也在真实数据中,这将导致错误。编辑:每个对象之间也缺少逗号。
  • 我没有看到问题(也许我遗漏了一些东西)但是当我尝试获取响应时,这看起来非常好,而且当我转到给定的链接时,chrome 正在向我显示常规的 JSON,看起来像这样: [ { "userId": 1, "id": 1, "title": "delectus aut autem", "completed": false },....]
  • 天哪,我的错。我不假思索地翻译了页面,它弄乱了格式。 :facepalm:

标签: ruby


【解决方案1】:

这里是工作代码 sn-p:

require 'httpclient'
require 'json'

client = HTTPClient.new
method = 'GET'
url = URI.parse 'https://jsonplaceholder.typicode.com/todos'
res = client.request method, url
dd = JSON.parse(res.body)

# Use word['completed'] instead of word.completed here:
puts dd.select { |word| !word['completed'] }

# Use 'any?' array (Enumerable) method to check
# if any member of the array satisfies given condition:
puts dd.any? { |word| word['title'] == 'temporibus atque distinctio omnis eius impedit tempore molestias pariatur' }

#any? 的文档可以在这里找到:https://apidock.com/ruby/Enumerable/any%3F

【讨论】:

  • 哇,这就像一个魅力。谢谢你的帮助(我试图检查这是正确的答案,但我没有正确的声誉点数)。
  • 不客气。嗯,无论您的声誉如何,您都应该能够接受答案。试试这个:meta.stackexchange.com/questions/5234/…
  • 完成。谢谢
猜你喜欢
  • 1970-01-01
  • 2018-06-30
  • 1970-01-01
  • 2021-01-17
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2022-01-10
相关资源
最近更新 更多