2012-08-01 104 views
3

从JSON文件中的值这是一个sample.json文件如下解析在红宝石

{ 
"name": "Jack (\"Bee\") Nimble", 
"format": { 
    "shape": "rect", 
    "width": 1920, 
    "height": 1080, 
    "interlace": false, 
    "framerate": 24 
} 
} 

在sample.json文件已被打开的规格文件。

describe Samplespec do 
    before :all do 
    @jsonfile = File.open('sample.json').read 
    @file_json = Samplespec.new(@jsonfile) 
end 

我在sample.rb文件

require 'json' 
def initialize(val) 
@parsed_val = JSON.parse(val) 
end 

这似乎并不工作写这个。请帮忙。谢谢

+2

似乎没有工作?你会得到什么错误,会发生什么? – 2012-08-01 13:06:11

+0

sample.json文件原样显示{“name”:“Jack(\”Bee \“)Nimble”, “format”:{ “shape”:“rect”, “width”: 1920, “height”:1080, “interlace”:false, “framerate”:24 } } – user1568617 2012-08-01 13:08:40

回答

3

您可能会看到JSON.parse的输出与Ruby的Hash#to_s的格式与JSON大致相同。此代码(代码)工作对我来说:

json = '{ 
"name": "Jack (\"Bee\") Nimble", 
"format": { 
    "shape": "rect", 
    "width": 1920, 
    "height": 1080, 
    "interlace": false, 
    "framerate": 24 
} 
}' 

require 'json' 
def parse(val) 
@parsed_val = JSON.parse(val) 
end 

json = parse(json) 

puts json 
puts json['name'] 

所以,第一个puts会再次出现,以输出JSON(它只是哈希#to_s),但第二puts将正确的预期输出只是name关键。