I have a json file. I am using it to store information, and as such it is constantly going to be both read and written.
I am completely new to ruby and oop in general, so I am sure I am going about this in a crazy way.
class Load
def initialize(save_name)
puts "loading " + save_name
@data = JSON.parse(IO.read( $user_library + save_name ))
@subject = @data["subject"]
@id = @data["id"]
@save_name = @data["save_name"]
@listA = @data["listA"] # is an array containing dictionaries
@listB = @data["listB"] # is an array containing dictionaries
end
attr_reader :data, :subject, :id, :save_name, :listA, :listB
end
example = Load.new("test.json")
puts example.id
=> 937489327389749
So I can now easily read the json file, but how could I write back to the file – refering to example? say I wanted to change the id example.id.change(7129371289)… or add dictionaries to lists A and B… Is this possible?
The simplest way to go to/from JSON is to just use the
JSONlibrary to transform your data as appropriate:json = my_object.to_json— method on the specific object to create a JSON string.json = JSON.generate(my_object)— create JSON string from object.JSON.dump(my_object, someIO)— create a JSON string and write to a file.my_object = JSON.parse(json)— create a Ruby object from a JSON string.my_object = JSON.load(someIO)— create a Ruby object from a file.Taken from this answer to another of your questions.
However, you could wrap this in a class if you wanted:
The above behaves just like a hash, but you can use
foo = JSONHash.from("foo.json")to load from disk, modify that hash as you would normally, and then justfoo.savewhen you want to save out to disk.Or, if you don’t have a file on disk to begin with: