用ruby从字符串创建json对象

时间:2015-04-21 08:31:12

标签: ruby-on-rails ruby json

我对Ruby开发真的很新。我正在尝试使用字符串创建一个json文件。我的json文件如下。你能帮我吗

{
    "App":{
        "properties":{"color":"red"},
        "screens":[
                {"id":"page1", "properties":{"color":"red"}, "elements":[
                                                {"type":"txtbox", "properties":{"color":"red"}}, 
                                                {"type":"button", "properties":{"color":"red"}}
                                                ]
                },
                {"id":"page2", "properties":{"color":"red"}, "elements":[
                                                {"type":"txtbox", "properties":{"color":"red"}}, 
                                                {"type":"button", "properties":{"color":"red"}}
                                                ]
                }
        ]
    }
}

1 个答案:

答案 0 :(得分:15)

您可以从哈希中解析带有ruby的JSON:

require 'json'

my_hash = JSON.parse('{"hello": "goodbye"}')
puts my_hash["hello"] => "goodbye"

或者从哈希生成它:

require 'json'

my_hash = {:hello => "goodbye"}
puts JSON.generate(my_hash) => "{\"hello\":\"goodbye\"}"

查看JSON documentation