2012-01-04 44 views

回答

-1

您可以分析使用Ruby

data = ActiveSupport::JSON.decode(json_data) 

,然後簡單地遍歷數據,並使用它存儲在數據庫中的ActiveRecord

data["data"].each do |comment| 
    Comment.create!(:message => comment.message, ...) 
end 
+0

謝謝我如何創建json_data? – user1130493 2012-01-04 19:55:06

+0

特別是當我試圖從Facebook獲取它。就像我不想複製和粘貼所有文本到我的文件。是否有任何有效的方式通過傳遞我的鏈接來做到這一點? – user1130493 2012-01-04 20:01:18

0
的JSON

查看下面的代碼:

url_commented_on = "http://techcrunch.com/2012/01/04/mechanical-engineering-community-grabcad-grabs-4-million/" 
fb_comments_url = "https://graph.facebook.com/comments/?ids="+url_commented_on 
fb_comments_json = open(fb_comments_url).read 
fb_comments_data = ActiveSupport::JSON.decode(fb_comments_json) 

# If you want to play around, this gets you the first comment 
fb_comments_data[url_commented_on]["comments"]["data"].first 
# and this gets you the first comment's message 
fb_comments_data[url_commented_on]["comments"]["data"].first["message"] 

# You could save them in your db like this: 
fb_comments = fb_comments_data[url_commented_on]["comments"]["data"] 
fb_comments.each do |fb_comment| 
    # Your comment Model here 
    fb_commenter_name = fb_comment["from"]["name"] 
    fb_comment_message = fb_comment["message"] 
    fb_comment_creation_date = fb_comment["created_time"] 
    # Your comment Model 
    comment = CommentModel.new 
    comment.author = fb_commenter_name 
    comment.comment_text = fb_comment_message 
    # Don't overwrite your own "created_at" attribute 
    # Instead, use an additional column in the db for storing the date fb gives you 
    comment.fb_created_at = fb_comment_creation_date 
    comment.save! 
end