2

I'm parsing a JSON file in Ruby and want to output the results using pp to a file. How can I do that? Here's the code I'm trying:

require 'rubygems'
require 'json'
require 'pp'

json = File.read('players.json')
plyrs = JSON.parse(json)

File.open('plyrs.txt', 'a') { |fo| pp page, fo }
eskay
  • 21
  • 4

2 Answers2

2

require "rubygems" is redundant in Ruby >= 1.9.

require "json"
require "pp"

plyrs = JSON.load("players.json")
File.open("plyrs.txt", "a"){|io| io.write(plyrs.pretty_inspect)}
sawa
  • 165,429
  • 45
  • 277
  • 381
  • this returned: /Users/name/.rvm/rubies/ruby-1.9.2-p320/lib/ruby/1.9.1/json/common.rb:146:in `parse': 710: unexpected token at 'players.json' (JSON::ParserError) from /Users/name/.rvm/rubies/ruby-1.9.2-p320/lib/ruby/1.9.1/json/common.rb:146:in `parse' from /Users/name/.rvm/rubies/ruby-1.9.2-p320/lib/ruby/1.9.1/json/common.rb:294:in `load' from print_players.rb:32:in `
    '
    – eskay Sep 26 '13 at 08:15
1

Try this

require 'rubygems'
require 'json'
require 'pp'

json = File.read('players.json')
plyrs = JSON.parse(json)

File.open('plyrs.txt', 'a') { |file| file.write(pp plyrs) }

More info available at the ruby documentation

Momer
  • 3,158
  • 22
  • 23