Search code examples
jsonrubysinatra

Ruby: From a String to an Array of JSONS


I have a string retrieved from a post form which looks something like that

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

I would like to iteratively access every JSON object on its own. Or Ideally, convert this string to an array of JSONs in Ruby. Any idea on how to do that?


Solution

  • Use 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"
        }
    ]