【问题标题】:Pass parameter from Json Httparty to ostruct将参数从 Json Httparty 传递给 ostruct
【发布时间】:2018-05-09 13:50:27
【问题描述】:

我想将响应中的数据放入集合中

require 'httparty'
require 'ostruct'
require 'nokogiri'

response = HTTParty.get('http://localhost:3000/api/v2/teste')
   #example response   {x:[{"testey":1213,"Testex":"2018-03-07"}]}

collection = [
  OpenStruct.new(
    :testex => '657758',
    :testey => 'CTH6536'
   )
]

【问题讨论】:

  • 只需传递“splattened”数组响应OpenStruct.new(*[{"testey":1213,"Testex":"2018-03-07"}])
  • 这个 json [{"testey":1213,"Testex":"2018-03-07"}] 是一个来自响应的例子,我想响应的参数是通过集合

标签: ruby-on-rails ruby ruby-on-rails-4 rubygems ruby-on-rails-3.2


【解决方案1】:

根据文档http://ruby-doc.org/stdlib-2.0.0/libdoc/json/rdoc/JSON.html#method-i-parse

JSON.parse(response.body, object_class: OpenStruct)

【讨论】:

  • 虽然这个答案可能是正确的,但添加解释会更有用。
【解决方案2】:

我找到了解决办法

response = HTTParty.get('http://localhost:3000/api/v2/teste')

response['x'].each do |aux|
  @msgx = aux['Testex']
  @msgy = aux['testey']
end

collection = [
  OpenStruct.new(
    :testex => @msgx,
    :testey => @msgy
   )
]

【讨论】:

  • 如果您得到 10 个字段的响应怎么办?
【解决方案3】:

你的回答很好,Andriy-baran,我用这种方法遇到的问题是“[” 回复我的回复:{x:[{"testey":1213,"Testex":"2018-03-07"}]}

response = HTTParty.get('http://localhost:3000/api/v2/teste')

如果答案是这样 {x:{"testey":1213,"Testex":"2018-03-07"}} 会这样做

response = HTTParty.get('http://localhost:3000/api/v2/teste')
xy = JSON.parse(response.body, object_class: OpenStruct)
puts xy.x.testey

【讨论】:

    猜你喜欢
    • 2016-11-04
    • 1970-01-01
    • 1970-01-01
    • 2018-04-26
    • 2021-03-22
    • 1970-01-01
    • 2018-04-12
    • 1970-01-01
    • 2020-04-13
    相关资源
    最近更新 更多