从 Json Httparty 传递参数到 ostruct

Pass parameter from Json Httparty to ostruct

我想从响应中获取数据放在集合中

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'
   )
]

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

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

我找到了解决办法

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
   )
]

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

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

If the answer were so {x:{"testey":1213,"Testex":"2018-03-07"}} would do it

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