In rails some times we are getting invalid json outputs say for example, as per the json standard, both the attributes and its values should be enclosed with double quotes (") but in some of the ruby patches has issues with that. If you are facing such issues then this post will be useful:
Changes what we have to make in the file 'core.rb' which is located at:
LIB_PATH/ruby/gems/1.8/gems/activesupport-1.4.0/lib/active_support/json/encoders
in your rails server, the LIB PATH is /usr/local/lib
required function is "encoder" line# 52
New Code
========
define_encoder Hash do |hash|
returning result = '{' do
result << hash.map do |key, value|
key = ActiveSupport::JSON::Variable.new(key.to_s) if
ActiveSupport::JSON.can_unquote_identifier?(key)
"\"#{key.to_json}\": #{value.to_json}" #=> This is line where we included the required quotes, thats it
end * ', '
result << '}'
end
end
Old Code
========
define_encoder Hash do |hash|
returning result = '{' do
result << hash.map do |key, value|
key = ActiveSupport::JSON::Variable.new(key.to_s) if
ActiveSupport::JSON.can_unquote_identifier?(key)
"#{key.to_json}: #{value.to_json}"
end * ', '
result << '}'
end
end
Output Sample: [Json attribute key should be enclosed with quotes]
Old code will produce the json output as follows:
[
{
person: {
id: 1,
last_name: "test"
}
}
]
New code will produce the json output as follows [Note the json attribute keys are enclosed with quotes]
[
{
"person": {
"id": 1,
"last_name": "test"
}
}
]
You can validate the json code at http://jsonlint.com/ , also the site http://jsonviewer.stack.hu/ will helps you understand the hierarchy of the json output.
Comments
Post a Comment