Ruby:从字符串到JSONS数组

时间:2018-03-24 12:53:07

标签: json ruby sinatra

我有一个从帖子表单中检索到的字符串,看起来像那样

"[{"Name": "David", "ID": "2"}, {"Name": "Logan" , "ID": "3"}]"

我想迭代地自己访问每个JSON对象。或者理想情况下,将此字符串转换为Ruby中的JSON数组。关于如何做到这一点的任何想法?

2 个答案:

答案 0 :(得分:1)

使用JSON.parse

require 'json'
=> true
JSON.parse('[{"Name": "David", "ID": "2"}, {"Name": "Logan" , "ID": "3"}]')
=>
[
    [0] {
        "Name" => "David",
          "ID" => "2"
    },
    [1] {
        "Name" => "Logan",
          "ID" => "3"
    }
]

答案 1 :(得分:0)

要将从API返回的JSON string转换为JSON字符串的Ruby数组,我会这样做:

json = '[{"Name": "David", "ID": "2"}, {"Name": "Logan" , "ID": "3"}]'

require 'json'

ruby_array_of_ruby_hashes = JSON.parse(json)
ruby_array_of_json = ruby_array_of_ruby_hashes.map(&:to_json)
#=> ["{\"Name\":\"David\",\"ID\":\"2\"}","{\"Name\":\"Logan\",\"ID\":\"3\"}"]

或简短:

JSON.parse(json).map(&:to_json)