【问题标题】:parsing the values from the json file in Ruby在 Ruby 中解析 json 文件中的值
【发布时间】:2012-07-30 09:13:12
【问题描述】:

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

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

【问题讨论】:

  • 似乎不起作用?你得到什么错误,会发生什么?
  • sample.json 文件按原样显示{ "name": "Jack (\"Bee\") Nimble", "format": { "shape": "rect", "宽度”:1920,“高度”:1080,“隔行”:假,“帧率”:24 } }

标签: ruby json rspec specifications


【解决方案1】:

您可能从 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 键。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-10-01
    相关资源
    最近更新 更多