How do I append/add data to an JSON file with Ruby
Of course, simply joining two JSON strings together don't work and would result in an invalid JSON. In your example, the hash you try to add would not end up in the array but behind.
The correct way is to read the existing JSON file and parse it into a RUBY data structure and add the new hash in Ruby to the array before writing everything back to JSON.
require 'json'
filename = '/root/Desktop/jsonDatabase.json'
hash = { "first_name" => "john", "last_name" => "doe" }
array = JSON.parse(File.read(filename)
array << hash
File.open(filename, 'w') do |f|
f.write(JSON.pretty_generate(array))
end
Append new values to an existing JSON array in ruby
In @scenario
you have Array
object, so if you wanna to add new hash inside this Array, just use Array#<< method like this.
Because the Array is object, you can add data inside this object.
new_scenario = {
"ScenarioNumber" => 2,
"ScenarioName" => "SC2",
"ScenarioDescription" => "Desc",
"ScExecutionStatus" => "Execution Complete",
"ScenarioStatus" => "In-Complete",
"ScenarioSeverity" => false,
"TestCase" => [
{
"TestCaseNumber" => 1,
"TestCaseName" => "Some Name ",
"TcExecutionStatus" => "Execution Error",
"TcStatus" => "NA",
"TcSeverity" => "NA"
}
]
}
@scenario << new_scenario
@template_file
now include new_scenario
Ruby - Append data to existing JSON
You can use Array#push
like this:
test = {
:provisioningState=>"Succeeded",
:resourceGuid=>"test",
:securityRules=>[
{:name=>"SSH", :id=>"SSH", :etag=>"18",:type=>"Microsoft/securityRules", :properties=>{}}
]
}
new_rule = {
:name => 'rule_2',
:properties => {
:protocol => 'TCP',
:sourceAddressPrefix => '*',
:destinationAddressPrefix => '*',
:access => 'Allow',
:destinationPortRange => '22',
:sourcePortRange => '*',
:priority => '301',
:direction => 'Inbound',
}
}
test[:securityRules].push(new_rule)
test
# {
# :provisioningState=>"Succeeded",
# :resourceGuid=>"test",
# :securityRules=> [
# {:name=>"SSH", :id=>"SSH", :etag=>"18", :type=>"Microsoft/securityRules", :properties=>{}},
# {:name=>"rule_2",:properties=>{:protocol=>"TCP",:sourceAddressPrefix=>"*",:destinationAddressPrefix=>"*",:access=>"Allow",:destinationPortRange=>"22",:sourcePortRange=>"*",:priori# ty=>"301",:direction=>"Inbound"}}
# ]
# }
Appending the data in JSON file using Ruby
Uri Agassi's code is perfect, but I thought to explain what went wrong in the OP code.
The Hash[]
expects an array of key, value
pairs (either as separate arguments or an array of arrays):
Hash[:a, 1, :b, 2] # => {:a=>1, :b=>2}
Hash[[[:a,1], [:b,2]]] # => {:a=>1, :b=>2}
But the original JSON contained Array of Hashes which gets parsed into corresponding Ruby objects as in the simplified case:
[{:a => 1}, {:b => 2}]
When you use the Ruby splat operator *
on the above array:
Hash[ *[{:a => 1}, {:b => 2}] ]
You efectively provide separate hashes as a key-value pair to the Hash constructor:
Hash[ {:a => 1}, {:b => 2} ] # => {{:a=>1} => {:b=>2}}
So, essentially, you got what you asked for: you turned a array of hashes into a hash of hashes and then you added that to a blank array and topped up with another hash.
Correct solution
Just to make the original code work with minimal changes (but still take a look at Uri's solution):
tempHash = {"Group_Name" => @GroupName, "Group_Logo_Code" => @GroupLogoCode }
json = File.read('public/group.json')
secondJsonArray = JSON.parse(json)
secondJsonArray << tempHash
File.open("public/group.json","w") do |f|
f.puts JSON.pretty_generate(secondJsonArray)
end
Add values to Ruby JSON Object
You could try this
json = { "data" => [
{"name" => "A", "available" => "1"},
{"name" => "B", "available" => "0"}
]}
json["data"].push({"name" => "C", "available" => "1"})
Ruby cant append to JSON file
rb_hash["searchExamples"]
is a hash and as @axiac said there is no <<
method on Hash class in ruby. Use Hash#merge to concatenate two hashes:
json = File.read(File.join( File.dirname(__FILE__),"configs/#{enviroment}.json"))
rb_hash = JSON.parse(json);
rb_hash["searchExamples"] = rb_hash["searchExamples"].merge({ name: "John", long: 20, lat: 45 })
# or rb_hash["searchExamples"].merge!({ name: "John", long: 20, lat: 45 })
File.write(File.join( File.dirname(__FILE__),"configs/#{enviroment}.json"), rb_hash.to_json)
Also you might want to use pretty generate gems like NeatJSON or JSON#pretty_generate for better json output in your file
Appending to JSON array in Ruby
First convert the JSON to a Ruby hash this way:
require 'json'
rb_hash = JSON.parse('<your json>');
rb_hash["data"] << { name: "John", long: 20, lat: 45 }
rb_hash.to_json
How to add new key/value pair to existing JSON object in Ruby
How could I append a new key/value pair to existing JSON object in Ruby?
If you want to add it to an existing file then you should read the JSON first, extract data from it, then add a new hash to an array.
Maybe something like this will solve your problem:
def create_book(name, author)
tempHash = {
SecureRandom.uuid => {
"name" => name,
"author" => author
}
}
data_from_json = JSON[File.read("./books/book.json")]
data_from_json = [data_from_json] if data_from_json.class != Array
File.open("./books/book.json","w") do |f|
f.write(JSON.pretty_generate(data_from_json << tempHash))
end
end
There are also some other ways like manipulating the JSON as a common string but for safety you should extract the data and then create a new JSON file.
how to append data to json in ruby/rails?
item = Item.find(params[:id])
item["message"] = "it works"
render :json => item.to_json
Related Topics
Rails "Template Is Missing" Error
How to Display Error Messages in a Multi-Model Form with Transaction
How to Make an Infowindow Automatically Display as Open with Google-Maps-For-Rails
Assets Precompiling Error with Jquery UI Plugin
How to Return the Number of Devise Users Currently Logged In
Loaderror - Cannot Open Shared Object File - File Is Present, But It Says No Such File
Delayedjob: "Job Failed to Load: Uninitialized Constant Syck::Syck"
When Passing a Ruby Array as an Argument, Why Does '<<' Append While '+=' Does Not
My Classes Can't Use Shoes Methods Like Para
Ruby Implementation Win32API Get Mouse Scroll/Wheel Input
Gracefully Shutting Down Sidekiq Processes