3

这是一个 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

这似乎不起作用。请帮忙。谢谢

4

1 回答 1

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(它只是 Hash#to_s),但第二个puts将按预期正确输出只是name键。

于 2012-08-01T14:21:11.407 回答