【问题标题】:Cannot Convert String and Fixnum to JSON in Rails 3无法在 Rails 3 中将字符串和 Fixnum 转换为 JSON
【发布时间】:2012-08-22 14:46:51
【问题描述】:
    JSON.parse('abc'.to_json) gives this error (in rails):

    JSON::ParserError: 757: unexpected token at '"abc"'
    from /Users/mpapper/.rvm/gems/ruby-1.9.2-p290@dfc-site/gems/json-1.7.4/lib/json/common.rb:155:in `parse'
    from /Users/mpapper/.rvm/gems/ruby-1.9.2-p290@dfc-site/gems/json-1.7.4/lib/json/common.rb:155:in `parse'
    from (irb):20
    from /Users/mpapper/.rvm/gems/ruby-1.9.2-p290@dfc-site/gems/railties-3.1.3/lib/rails/commands/console.rb:45:in `start'
    from /Users/mpapper/.rvm/gems/ruby-1.9.2-p290@dfc-site/gems/railties-3.1.3/lib/rails/commands/console.rb:8:in `start'
    from /Users/mpapper/.rvm/gems/ruby-1.9.2-p290@dfc-site/gems/railties-3.1.3/lib/rails/commands.rb:40:in `<top (required)>'
    from script/rails:41:in `require'
    from script/rails:41:in `<main>'

同样失败:

 JSON.parse(100.to_json)

这也是(略有不同的错误):

 JSON.parse(1.to_json)

为什么我不把输出的 json 包装在 {} 中,让它看起来像真正的 json? 因为我正在编写应该能够获取任何对象并将其序列化为 JSON 并再次将其拉回的代码。

我认为问题出在此:JSON 看起来像是一组编码的键值对,都放在 {} 中。但是 rails (3.x) 中的 to_json 方法根本不输出任何 {}。

鉴于此,我真正想要的只是一种将任意 ruby​​/rails 对象序列化为字符串并再次返回的简单方法。已经有很多对象有 to_json 方法(String、Fixnum、Array、Hash),但是 String 和 Fixnum 版本不生成可以解析的 Json。

【问题讨论】:

    标签: ruby-on-rails ruby json parsing


    【解决方案1】:

    JSON RFC,我们有声明

    JSON 文本是一个序列化的对象或数组。

    这几乎概括了它。在顶层,您的 JSON 必须是数组或对象之一。

    您的代码能否简单地执行以下操作:

    json = {'myprotocol' => whatever}.to_json
    result = JSON.parse(json)['myprotocol']
    

    【讨论】:

    • 谢谢,该代码有效。因此,由我的代码来获取 to_json 的输出并将其很好地打包。按照 Serge 的建议使用 ActiveSupport::JSON.decode 是一种更好的方法(对我来说)。
    【解决方案2】:

    这不是您要查找的 JSON。试试这个:

    ActiveSupport::JSON.decode('abc'.to_json)
    ActiveSupport::JSON.decode(1.to_json)
    

    【讨论】:

      猜你喜欢
      • 2011-04-15
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-10-31
      • 2011-09-11
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多