简体   繁体   English

如何在Ruby 1.8.7版中解析JSON文件

[英]How to parse a JSON file in Ruby version 1.8.7

I have a file called Output.json: 我有一个名为Output.json的文件:

[
  {
    "name": "krishna",
    "service": "postman",
    "host": "xxxxxx",
    "doing": [],
    "pool": "xxxxxx",
    "roleType": "yyyyy",
    "simple": true
  }
 ]

And this is my Test.rb file: 这是我的Test.rb文件:

require 'rubygems'
require 'json'
require 'pp'

file = File.read('output.json')
data_hash= JSON.parse(file)
pp data_hash

When I try to run the script I get: 当我尝试运行脚本时,我得到:

from /usr/lib/ruby/gems/1.8/gems/json-1.4.6/lib/json/common.rb:146:in `parse'

How do I print the value "krishna" when I call the name from the JSON file. 当我从JSON文件中调用名称时,如何打印值“ krishna”。

Although I never tried version 1.8.7 (only 1.9.3 and higher) 虽然我从未尝试过1.8.7版(仅1.9.3和更高版本)

I would assume your problem is that you aren't reading the file correctly. 我认为您的问题是您没有正确读取文件。 Try File.open instead 试试File.open代替

Try this: 尝试这个:

file = File.open('output.json').read
data_hash = JSON.parse(file)
pp data_hash

as for printing the value krishna try this (after parsing): 至于打印值克里希纳尝试此(解析后):

puts data_hash['name']  # this outputs krishna

Good luck 祝好运

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM