我在文本文件中有一个哈希,但是当我运行以下命令时,我得到了一个JSONParseError 757。
file = File.open("output.txt", "r")
test = JSON.parse(file.to_json)
但是,当我手动输入散列时,我的测试工作正常。
test = JSON.parse(({test=>test}).to_json)
有什么想法吗?
编辑:(生成的日志在这里)
[2] pry(main)> data_hash = JSON.parse(file)
JSON::ParserError: 399: unexpected token at '{"id"=>"tag:search.twitter.com,2005:738647950117593089", "objectType"=>"activity", "verb"=>"post", "postedTime"=>"2016-06-03T08:26:09.000Z", "generator"=>{"displayName"=>"Facebook", "link"=>"http://www.facebook.com/twitter"}, "provider"=>{"objectType"=>"service", "displayName"=>"Twitter", "link"=>"http://www.twitter.com"}, "link"=>"http://twitter.com/AliyuAchimugu/statuses/738647950117593089", "body"=>"Kwara Govt. urges farmers to embrace modern farming to boost food security.\n\nSee details... ", "actor"=>{"objectType"=>"person", "id"=>"id:twitter.com:1317525900", "link"=>"http://www.twitter.com/AliyuAchimugu", "displayName"=>"Achimugu Aliyu", "postedTime"=>"2013-03-31T02:04:27.000Z", "image"=>"https://abs.twimg.com/sticky/default_profile_images/default_profile_5_normal.png", "summary"=>"Humanitarian | Entrepreneur |Great Survivor | Social Entrepreneur | Passionately Curious | Always Willing to Learn", "friendsCount"=>16, "followersCount"=>214, "listedCount"=>43, "statusesCount"=>161004, "twitterTimeZone"=>nil, "verified"=>false, "utcOffset"=>nil, "preferredUsername"=>"AliyuAchimugu", "languages"=>["en"], "links"=>[{"href"=>"https://facebook.com/AchimuguNoni", "rel"=>"me"}], "location"=>{"objectType"=>"place", "displayName"=>"Abuja,Nigeria"}, "favoritesCount"=>0}, "object"=>{"objectType"=>"note", "id"=>"object:search.twitter.com,2005:738647950117593089", "summary"=>"Kwara Govt. urges farmers to embrace modern farming to boost food security.\n\nSee details... ", "link"=>"http://twitter.com/AliyuAchimugu/statuses/738647950117593089", "postedTime"=>"2016-06-03T08:26:09.000Z"}, "favoritesCount"=>0, "twitter_entities"=>{"hashtags"=>[], "urls"=>[{"url"=>"test", "expanded_url"=>"test", "display_url"=>"test", "indices"=>[92, 115]}], "user_mentions"=>[], "symbols"=>[]}, "twitter_lang"=>"en", "retweetCount"=>0, "gnip"=>{"matching_rules"=>[{"value"=>"lang:en (argiculture OR farming) (ad leader OR data OR driverless OR gps OR internet of things OR iot OR john deere OR mobile OR monsanto OR security OR sensors OR tech OR technology OR toro) ", "tag"=>nil}], "urls"=>[{"url"=>"test", "expanded_url"=>"https://www.facebook.com/naijacomedyjokes/posts/1124075157654916", "expanded_status"=>nil, "expanded_url_title"=>nil, "expanded_url_description"=>nil}]}, "twitter_filter_level"=>"low"}]
'
from /home/blau08/.rvm/gems/ruby-2.1.2/gems/json-1.8.2/lib/json/common.rb:155:in `parse'
答案 0 :(得分:1)
请执行以下步骤:
#1 Require JSON
gem install json
#2 Open JSON file for Parsing
file = File.read('file-name-to-be-read.json')
#3 Parse Data from File
data_hash = JSON.parse(file)
提示:
file = File.read("output.txt")
test = JSON.parse(file)
答案 1 :(得分:0)
事实证明我必须把它写成JSON。无法将Ruby对象写入文件。