Ruby从API响应创建数组

时间:2018-11-11 04:50:08

标签: arrays ruby rest rest-client

如何创建数组或将剩余api响应存储到数组

剩余API响应

{"functionality":[],"subfunctionality":   [{"id":1,"title":"a1","description":"sample}, 
{"id":2,"title":"a2","description":"sample}, 
{"id":3,"title":"a3","description":"sample}

我希望将结果存储在数组中,如下所示

a[0]={"id":1,"title":"a1","description":"sample}
a[1]={"id":2,"title":"a2","description":"sample}
a[2]={"id":3,"title":"a3","description":"sample}]}

2 个答案:

答案 0 :(得分:0)

GroupAdd, TextEditor, ahk_class Notepad++
GroupAdd, TextEditor, ahk_exe Code.exe
GroupAdd, TextEditor, ahk_class Notepad

为我工作。

答案 1 :(得分:0)

我假设您显示的是“其余API响应”。如果是这样,则需要对其进行清理,以使其成为有效的JSON字符串,然后将其转换为哈希,然后提取所需的数组。

function Foo() {
  const memoizedHandleClick = useCallback(
    () => {
      console.log('Click happened');
    },
    [], // Tells React to memoize regardless of arguments.
  );
  return <Button onClick={memoizedHandleClick}>Click Me</Button>;
}

步骤如下。

str =<<_
{ "functionality":[], "subfunctionality": [{"id":1, "title":"a1", "description":"sample},
{"id":2, "title":"a2", "description":"sample}, 
{"id":3, "title":"a3", "description":"sample}
_

require 'json'

a = JSON.parse(str.gsub("\"sample", "\"sample\"") << ']}')["subfunctionality"]
  #=> [{"id"=>1, "title"=>"a1", "description"=>"sample"},
  #    {"id"=>2, "title"=>"a2", "description"=>"sample"},
  #    {"id"=>3, "title"=>"a3", "description"=>"sample"}]

请注意,为了方便阅读,我在各个地方都打断了字符串s = str.gsub("\"sample", "\"sample\"") << ']}' #=> "{ \"functionality\":[], \"subfunctionality\": [{\"id\":1, \"title\":\"a1\", # \"description\":\"sample\"},\n{\"id\":2, \"title\":\"a2\", # \"description\":\"sample\"}, \n{\"id\":3, \"title\":\"a3\", # \"description\":\"sample\"}\n]}" h = JSON.parse(s) #=> {"functionality"=>[], # "subfunctionality"=>[{"id"=>1, "title"=>"a1", "description"=>"sample"}, # {"id"=>2, "title"=>"a2", "description"=>"sample"}, # {"id"=>3, "title"=>"a3", "description"=>"sample"}]} h["subfunctionality"] #=> (return value shown above)