解析JSON数据时遇到麻烦

时间:2011-03-06 14:24:27

标签: ruby-on-rails ruby json parsing ruby-on-rails-3

解析以下JSON数据有什么问题

'{
   {"errors":
     {"firstname":"is too short"}
   },
   {"account":
     {"firstname":"Test"}
   }
}'

获取此错误?

JSON::ParserError in AccountsController#home
706: unexpected token at ... # the code above

在AccountsController中,我有

JSON.parse(json_data)["errors"]

3 个答案:

答案 0 :(得分:4)

您不应封装属性错误和帐户。它应该看起来像这样:

'{
  "errors":{"firstname":"is too short"},
  "account":{"firstname":"Test"}
}'

答案 1 :(得分:3)

您缺少属性名称:

'{"property1":
   {"errors":
     {"firstname":"is too short"}
   },
  "property2":
   {"account":
     {"firstname":"Test"}
   }
}'

或者,你真的想要一个数组:

'[
   {"errors":
     {"firstname":"is too short"}
   },
   {"account":
     {"firstname":"Test"}
   }
]'

答案 2 :(得分:1)

您的数据结构似乎是一个JSON对象{},但您有一个数组[]。第一组{}应为[]。

http://www.jsonlint.com/