how to append data to json in ruby/rails?
item = Item.find(params[:id])
item["message"] = "it works"
render :json => item.to_json
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
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
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"}}
# ]
# }
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"})
Appending to Json Array in ruby on rails
This should work for you:
render json: User.all.to_json(include: :tags)
or alternatively (just tag names):
render json: User.all.to_json(methods: :tag_list)
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
Append data from different model in json object
You may need to play with rails relationship here.
General speaking, your Question hasMany Like, and Like belongsTo Question
. Same goes to Answer, Answer hasMany Like, and Like belongsTo Answer
.
Since Like
can belongsTo
more than one model, you can try using Polymorphism Association
.
http://guides.rubyonrails.org/association_basics.html#polymorphic-associations
How to add item to json object ruby on rails?
You can write a custom method in your model and call it in index action, which returns all the costs with the username like below:
def self.list_costs
cost_list = []
costs = Cost.all
costs.each do |cost|
cost_info = cost.attributes
cost_info[:user_name] = cost.user.name
cost_list << cost_info
end
cost_list
end
class CostsController < ApplicationController
def index
render json: {costs: Cost.cost_list }
end
end
Related Topics
Generating a Short Uuid String Using Uuidtools in Rails
Certificate Verify Failed in "Gem Install Foundation"
Can't Install Rmagick, Pkg-Config: Command Not Found
Ruby on Rails, Paperclip, Amazon Aws S3 & Heroku
Rails Sort Tags by Most Used (Tag.Posts.Count)
How to Make Users Automatically Follow Admin User on Sign Up
Jekyll: How to Use Custom Plugins with Github Pages
Do You Know an Alternative Ctags Generator for Ruby
Ruby/Ror: Calling Original Method via Super()
Ruby on Rails: If Current Page? Is Homepage, Don't Show Form
Get the Name of a Local Variable
Netbeans 6.9.1 + Rails 3 + Ruby 1.9.2P0 Debugging
String Interpolation When Not Using a String Literal
Ruby: Titleize: How to Ignore Smaller Words Like 'And', 'The', 'Or, etc
Check Time Between 9.30 to 4 Ruby