【问题标题】:How to parse a JSON friend list to hash in Ruby?如何解析 JSON 好友列表以在 Ruby 中散列?
【发布时间】:2012-07-20 11:47:57
【问题描述】:

我在一些文件中包含这个 json 部分(来自 FACEBOOK API):

--- !seq:Koala::Facebook::API::GraphCollection - name: pop ool id: "1032225" - name: Rose kak id: "2312010"

在 ruby​​ 中我尝试这样做:

jsonFriends = File.open("friends.json" ,"r")

puts JSON.parse(jsonFriends.readline)

但我收到此错误:

from /usr/local/Cellar/ruby/1.9.3-p194/lib/ruby/1.9.1/json/common.rb:148:in `parse' from try.rb:22:in `<main>'

【问题讨论】:

  • 在我看来这根本不像 JSON。
  • 确实,这在我看来很像 YAML

标签: ruby json koala


【解决方案1】:

那是YAML,而不是JSON

require 'yaml'

friends = YAML.load(File.read('friends.json'))

【讨论】:

  • /usr/local/Cellar/ruby/1.9.3-p194/lib/ruby/1.9.1/psych.rb:203:in parse': (&lt;unknown&gt;): block sequence entries are not allowed in this context at line 1 column 48 (Psych::SyntaxError) from /usr/local/Cellar/ruby/1.9.3-p194/lib/ruby/1.9.1/psych.rb:203:in parse_stream' 来自 /usr/local/Cellar /ruby/1.9.3-p194/lib/ruby/1.9.1/psych.rb:151:in parse' from /usr/local/Cellar/ruby/1.9.3-p194/lib/ruby/1.9.1/psych.rb:127:in load' from try.rb:24:in `
    '
【解决方案2】:

试试看

require 'json'
result = File.read("friends.json")
puts JSON.parse(result)

【讨论】:

  • result = File.read("issues.json") p result # "{\"status\":801,\"errors\":[\"Failed login for '\"]}\n" --------------- r = File.open("issues.json",'r') p r ##&lt;File:issues.json&gt; Open 只是打开那个文件而不是读取它。
猜你喜欢
  • 2016-07-25
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2016-10-15
  • 2019-06-03
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多