How can I update a json file in ruby? [duplicate] - ruby

I am creating a hash in Ruby and want to write it to a JSON file, in the correct format.
Here is my code:
tempHash = {
"key_a" => "val_a",
"key_b" => "val_b"
}
fJson = File.open("public/temp.json","w")
fJson.write(tempHash)
fJson.close
And here is the contents of the resulting file:
key_aval_akey_bval_b
I'm using Sinatra (don't know what version) and Ruby v 1.8.7.
How can I write this to the file in the correct JSON format?

Require the JSON library, and use to_json.
require 'json'
tempHash = {
"key_a" => "val_a",
"key_b" => "val_b"
}
File.open("public/temp.json","w") do |f|
f.write(tempHash.to_json)
end
Your temp.json file now looks like:
{"key_a":"val_a","key_b":"val_b"}

With formatting
require 'json'
tempHash = {
"key_a" => "val_a",
"key_b" => "val_b"
}
File.open("public/temp.json","w") do |f|
f.write(JSON.pretty_generate(tempHash))
end
Output
{
"key_a":"val_a",
"key_b":"val_b"
}

This question is for ruby 1.8 but it still comes on top when googling.
in ruby >= 1.9 you can use
File.write("public/temp.json",tempHash.to_json)
other than what mentioned in other answers, in ruby 1.8 you can also use one liner form
File.open("public/temp.json","w"){ |f| f.write tempHash.to_json }

To make this work on Ubuntu Linux:
I installed the Ubuntu package ruby-json:
apt-get install ruby-json
I wrote the script in ${HOME}/rubybin/jsonDEMO
$HOME/.bashrc included:
${HOME}/rubybin:${PATH}
(On this occasion I also typed the above on the bash command line.)
Then it worked when I entered on the command line:
jsonDemo

Related

How to parse and send whole complicated XML from code in Rails

So I have this complicated XML and want it to parse it to array and send by Savon to the server. The question is how can I parse parameters?
<soapenv:Header>
<add:MessageID
xmlns:add="http://www.w3.org">sdhuf78dd67-8932
</add:MessageID>
<add:Action
xmlns:add="http://www.w3.org/2005">http://google/FMP
</add:Action>
<add:To
xmlns:add="http://www.w3.org/2005/08/addressing">https://no1.testbla.com/1HAD9ANA1
</add:To>
<link:TransactionFlowLink
xmlns:link="http://google/2010/06/"/>
<oas:Security
xmlns:oas="http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-wssecurity-secext-1.0.xsd">
<oas:UsernameToken oas1:Id="UsernameToken-1"
xmlns:oas1="http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-wssecurity-utility-1.0.xsd">
<oas:Username>AHOJHOLA</oas:Username>
<oas:Nonce EncodingType="http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-soap-message-security-1.0#Base64Binary">Nonce</oas:Nonce>
<oas:Password Type="http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-username-token-profile-1.0#PasswordDigest">HashedPassword</oas:Password>
<oas1:Created>CurrentGMTDateAndTime</oas1:Created>
</oas:UsernameToken>
</oas:Security>
<AMA_SecurityHostedUser
xmlns="http://xml.amfds.com/2010/06">
<UserID AgentDutyCode="DA" RequestorType="BO" PseudoCityCode="HIATRA67" POS_Type="5"/>
</AMA_SecurityHostedUser>
</soapenv:Header>
I know how to parse for example add:Action without parameter:
"add:Action" => "http://google/FMP"
And I know that parameter should be written with # prefix.
But I dont know how to write it together. Is this right?
"add:Action" => {
"#xmlns:add" => "http://www.w3.org/2005",
"http://google/FMP"
},etc.
To find out this information, you need to go and have a look at the Gyoku gem: the gem that Savon uses to translate Ruby hashes into XML. Specifically, the documentation on using explicit XML attributes. Looking at that, we can get the XML you're looking for with the following hash:
{
"add:Action" => {
"#xmlns:add" => "http://www.w3.org/2005",
:content! => "http://google/FMP"
}
}
We can test this in IRB directly with Gyoku:
irb> require 'gyoku'
# => true
irb> Gyoku.xml({"add:Action" => { "#xmlns:add" => "http://www.w3.org/2005", :content! => "http://google/FMP" } })
# => "<add:Action xmlns:add=\"http://www.w3.org/2005\">http://google/FMP</add:Action>"

Upload file with Mechanize for Ruby

File upload does not work using:
form.file_upload_with(:name => 'image[1]').file_name = '/tmp/image.jpg'
form.submit
This is an out-of-date example: https://github.com/sparklemotion/mechanize/blob/master/examples/flickr_upload.rb
I tried this on two different sites.
I'm using Mechanize 2.6.0.
Slightly off-topic, but another way to upload files with Mechanize I found useful, particularly if you don't have a HTML form handy, is to just use Mechanize.post with a File instance:
a = Mechanize.new
a.post(url, {
"file1" => File.new("/tmp/image.jpg")
})
Try this:
file = File.join( APP_ROOT, 'tmp', 'image.jpg')
form.file_uploads.first.file_name = file
Try:
form_with(:method => /POST/) do |form|
form.file_uploads.first.file_name = '/tmp/image.jpg'
end.submit

Rails 3.1 urllib2.quote(json.dumps(var)) Equivalent

In Python I can convert JSON into a useable encoded string eg:
cmd2 = [{'cmd': 'inlinepush',
'params': {'raw': 'score'
}
}]
url = urllib2.quote(json.dumps(cmd2))
print url
This produces:
%5B%7B%22cmd%22%3A%20%22inlinepush%22%2C%20%22params%22%3A%20%7B%22raw%22%3A%20%22score%22%7D%7D%5D
I have searched and searched but not found a Ruby or Rails equivalent, particularly in the NET::HTTP library.
I really have spent a lot of time thrashing to no end and would be grateful of any pointers.
Try this:
require 'cgi'
require 'json'
cmd2 = [{
'cmd' => 'inlinepush',
'params' => {
'raw' => 'score'
}
}]
puts CGI.escape(JSON.dump(cmd2))

How to write to a JSON file in the correct format

I am creating a hash in Ruby and want to write it to a JSON file, in the correct format.
Here is my code:
tempHash = {
"key_a" => "val_a",
"key_b" => "val_b"
}
fJson = File.open("public/temp.json","w")
fJson.write(tempHash)
fJson.close
And here is the contents of the resulting file:
key_aval_akey_bval_b
I'm using Sinatra (don't know what version) and Ruby v 1.8.7.
How can I write this to the file in the correct JSON format?
Require the JSON library, and use to_json.
require 'json'
tempHash = {
"key_a" => "val_a",
"key_b" => "val_b"
}
File.open("public/temp.json","w") do |f|
f.write(tempHash.to_json)
end
Your temp.json file now looks like:
{"key_a":"val_a","key_b":"val_b"}
With formatting
require 'json'
tempHash = {
"key_a" => "val_a",
"key_b" => "val_b"
}
File.open("public/temp.json","w") do |f|
f.write(JSON.pretty_generate(tempHash))
end
Output
{
"key_a":"val_a",
"key_b":"val_b"
}
This question is for ruby 1.8 but it still comes on top when googling.
in ruby >= 1.9 you can use
File.write("public/temp.json",tempHash.to_json)
other than what mentioned in other answers, in ruby 1.8 you can also use one liner form
File.open("public/temp.json","w"){ |f| f.write tempHash.to_json }
To make this work on Ubuntu Linux:
I installed the Ubuntu package ruby-json:
apt-get install ruby-json
I wrote the script in ${HOME}/rubybin/jsonDEMO
$HOME/.bashrc included:
${HOME}/rubybin:${PATH}
(On this occasion I also typed the above on the bash command line.)
Then it worked when I entered on the command line:
jsonDemo

Ruby: Can't save document with Libxml-ruby

From the libxml-ruby API docs (http://libxml.rubyforge.org/rdoc/index.html), under LibXML::XML::Document, I tried the following:
filename = 'something.xml'
stats_doc = XML::Document.new()
stats_doc.root = XML::Node.new('root_node')
stats_doc.root << XML::Node.new('elem1')
stats_doc.save(filename, :indent => true, :encoding => 'utf-8')
... which resulted in this error:
parse_stats.rb:26:in `save': can't convert String into Integer (TypeError)
(where the last line in the block above was line 26).
I tried changing the file name to an integer, which gave me this:
parse_stats.rb:26:in `save': wrong argument type Fixnum (expected String) (TypeError)
So I gathered that I need to use a string, but strings don't seem to work. Since I seem to be unable to find any examples of libxml-ruby in action off Google, I'm at a loss. Any help would be very appreciated, or links to any online example where I can see how libxml-ruby is used for creating XML documents.
libxml-ruby 1.1.3
rubygems 1.3.1
ruby 1.8.7
Seems that the problem is with encoding. Try XML::Encoding::UTF_8 instead of "utf-8".
require 'rubygems'
require 'libxml'
filename = 'something.xml'
stats_doc = LibXML::XML::Document.new()
stats_doc.root = LibXML::XML::Node.new('root_node')
stats_doc.root << LibXML::XML::Node.new('elem1')
stats_doc.save(filename, :indent => true, :encoding => LibXML::XML::Encoding::UTF_8)

Resources