开发者

How do you print JSON from the mongdb ruby driver?

开发者 https://www.devze.com 2023-01-09 23:06 出处:网络
When I do a find query from the mongodb JavaScript console, I get a beautiful JSON response. However, when I do a find with the ruby driver, it stores the 开发者_高级运维JSON as some Ruby object. How

When I do a find query from the mongodb JavaScript console, I get a beautiful JSON response. However, when I do a find with the ruby driver, it stores the 开发者_高级运维JSON as some Ruby object. How do I convert this back to JSON? Or, better yet, how do I just get the JSON without doing the extra conversions?


I got it working. I was using ruby-1.9.1-p378 with rvm. I removed that. Now, I'm using the system ruby-1.8.7-p174 that came with the SnowLeopard install DVD. But, I was still getting an error with the to_json method except this time it was saying, stack level too deep. I did:

require 'json/pure'

instead of

require 'json'

Then, I changed the code to look something like this: http://github.com/banker/mongulator/blob/master/mongulator.rb#L53

Here's the relevant part of the code:

cursor = persons.find(
  {"loc" => {"$near" => [params[:lat].to_f, params[:lng].to_f]}},
  {:limit => 20})
content_type "application/json"
JSON.pretty_generate(cursor.to_a)

The complete file is here: http://github.com/acani/acani-sinatra/blob/master/acani.rb

And, it worked, even with pretty json like the facebook graph api gives you. To return the JSON all on one line, just do something like:

  cursor.to_a.to_json


The JSON Code you get on the javascript console is also converted. It's not the native output of MongoDB, the Native format is BSON. To Get JSON on the javascript console it must be converted. In Ruby you should be able to do the same thing with the .to_json instance method of your Object.


now you can do cursor.find.to_a.inspect

0

精彩评论

暂无评论...
验证码 换一张
取 消