Okay, I am using HTTParty to save a JSON response in my show.subsources column. Subsources is a text type column.
For example, one of my subsources: column currently has the data saved as so:
[{"source"=>"hulu_free", "display_name"=>"Hulu", "id"=>6001348,"link"=>"http://www.hulu.com/watch/843378"}]
To me, this looks like a hash within an array. How do I access each hash within the array, so that I can correctly display the "source" name in my views?
What I have tried is:
<% showdata = show.subsources %>
<%= showdata[0]['sources'] %>
I am expecting that to display 'hulu_free', but instead it will not show anything in my views. Am I not using the right syntax to access that hash? Or am I not saving the JSON correctly in order for me to access the hash data? Do I need to parse the data first? I have spent way too long trying to figure this out.
In your case you can easily get JSON representation and parse it to Hash.
text = text = %q{[{"source"=>"hulu_free", "display_name"=>"Hulu", "id"=>6001348,"link"=>"http://www.hulu.com/watch/843378"}]}
text.gsub!('=>',':')
JSON.parse(text) # => returns hash
I'm not sure how internals work in your program, but probably you should consider to put JSON like text into this field.
Related
I have problem with convert array with hashes to json. But i need to have that same keys in hash with different values.
elements = []
portal_order_items.each do |product|
elements << {"Kod":product.Kod,"Cena"=>product.price,"Ilosc"=>product.quantity}
end
And i get something like this:
[{:Kod=>"M06006P0232", "Cena"=>"2.0", "Ilosc"=>1}, {:Kod=>"M06006P0019", "Cena"=>"53.0", "Ilosc"=>1}]
How chage it to json like this:
{"Kod":"M06006P0232", "Ilosc":1, "Cena":2.0,"Kod":"M06006P0019", "Ilosc":22, "Cena":53.0}
It need to be one json.. Anyone know solution of my problem ?
You can generate a string you need like this:
portal_order_items.map { |item| JSON.generate(item) }.join(',').gsub(/},{/, ',')
However, be advised that this JSON has duplicate keys. While this is technically correct (there is no explicit requirement for JSON document to have unique keys), most libraries out there will just keep the last key's value when parsing it. Most likely, this is not what you want.
You should be able to use .map to edit your array of portal_order_items and then you can covert to json using .to_json method.
See the docs for JSON here.
portal_order_items.map do |product|
{"Kod":product.Kod,"Cena"=>product.price,"Ilosc"=>product.quantity}
end.to_json
I'm pretty new to Ruby, and I'm using it work with an API. Text area's sent over the API are converted to the format below before being sent to me via a JSON POST request:
"Comment": [
"hdfdhgdfgdfg\r",
"This is just a test\r",
"Thanks!\r",
"- Kyle"
]
And I'm getting the value like this:
comments = params["Comment"]
So each line is broken down into what looks like an array. My issue is, it functions just like one big string instead of an array with 4 values. I tried using comments[0] and just printing comments but both return the same result, it just displays everything as a string, ie
["hdfdhgdfgdfg\r", "This is just a test\r", "Thanks!\r", "- Kyle"]
But I need to display it as it appears in the text area, ie
hdfdhgdfgdfg
This is just a test
Thanks!
- Kyle
I know I could just strip out all the extra characters, but I feel like there has to be a better way. Is there a good way to convert this back to the original format of a text area, or at least to convert it to an array so I can loop through each item and re-format it?
First, get rid of those ugly \rs:
comments.map!(&:chomp)
Then, join the lines together:
comment = comments.join("\n") # using a newline
# OR, for HTML output:
comment = comments.join('<br>')
You should be able to parse the JSON and populate a hash with all of the values:
require 'json'
hash = JSON.parse(params["Comment"])
puts hash
=> {"Comment"=>['all', 'of', 'your', 'values']}
This should work for all valid json. One of the rules of json syntax is that
Data is in name/value pairs
The json you provided doesn't supply names for the values, therefore this method might not work. If this is the case, parsing the raw string and extracting values would do the job as well (although more messy).
How you might go about doing that:
json = params["Comment"]
newArray = []
json.split(" ").each do |element|
if element.length > 1
newArray << element
end
end
This would at least give you an array with all of your values.
I am trying to execute two helper functions of in a view call the second with the return of the first. I know the following functions properly returns the desired hash:
%p = helper_method0 params[:some_string] #does a request on a third party site which responds with json data wich is then parsed by yajl and the hash is returned to view
However when I call the following:
- hash = helper_method0 params[:some_string] #does a request on a third party site which responds with json data wich is then parsed by yajl and the hash is returned to view
%p= helper_method1 hash #Literally is just returning the input parameter
I receive the following error message
Found multiple JSON objects in the stream but no block or the on_parse_complete callback was assigned to handle them.
How do I call a method with an input parameter as the return of another method from the view?
What you are doing is perfectly correct :)
And you could also do:
(if you want to save bytes and variables)
%p= helper_method1( helper_method0 params[:some_string] )
But anyway...
This error sounds like a problem in the json parser... are you using Yajl?
I have seen this issue when using Yajl like this:
parser = Yajl::Parser.new
hash = parser.parse(some_string)
What worked for me was to use the Yajl class method like this:
Yajl::Parser.parse(some_string.strip)
I hope this helps :)
I want to display raw data of one value from database. Table is quite big, with a lot of data and i need only 5 columns on index page. So i defined needed columns in criteria and used doSelectStmt with pager to paginate result.
Im displaying it like this:
http://pastebin.com/bccSkjs1
TEXT field contains some HTML and i want to display it normally (not escaped). However, 3 other fields (not show in code above) have to be escaped, because they can have some html too, but it cannot by interpreted as html.
I know that in normal object, i can do: $sf_data->getRaw("foo")->getBar() instead of $foo->getBar() to get expected result.
But how i can get same, when i dont have normal object, only array of data like in this case?
I know i can do $sf_data->getRaw("pager")->getResults() in a foreach, but it will unescape ALL fields which is tottal wrong!
Do you have to access the properties via arrays (which is ugly btw)?
If you were accessing the properties via the object getter methods, you could do:
echo $News->getText(ESC_RAW);
And your text field would be escaped.
I need to produce a date in Rails which looks like this:
/Date(1294268400000)/
I have tried various combinations of DateTime, to_i, to_json but never managed to get the /Date()/ thing.
Do I have to simply get my date in ms and then wrap the /Date(and )/ manually, or is there a built in method?
What about (ruby 1.9.x)?:
Time.now.strftime("/Date(%s%L)/")
=> "/Date(1335280866211)/"
You should try
new Date(posixMillisecondsHere)
first. MDN says that calling the Date function outside of the constructor context (i.e., without the new) will always return a string containing a formatted date rather than a Date object.
Strictly speaking, when you do that, you are writing JavaScript and not JSON. JSON cannot contain Date objects.
RFC 4627 says
2.1. Values
A JSON value MUST be an object, array, number, or string, or one of
the following three literal names:
false null true
If you want to put a Date into what is strictly considered JSON and then get it back out, you must choose some way of using the JSON primitives (to wit, objects, arrays, numbers, strings, etc.) to encode a Date.
If you want to get a Date back out of JSON, whatever parses your JSON must understand the convention that you used to encode the Date.
Hope these are credible and/or official enough to help.
What about something like this:
in your config/en.yml file:
en:
time:
formats:
json: "/Date(%s%L)/"
and than in the view:
<%= l(Time.now, :format => :json) %>
Please note that you would need access to the helpers in the method that renders json. So it won't work if you are using ActiveRecord#to_json method for generating jsons.
Check out this question:
c# serialized JSON date to ruby
... simple answer seems to be to create a parse_date method.
It's the UNIX Epoch (seconds since 1970-01-01) right? What about using DateTime#strftime method?
# Taken from the Ruby documentation
seconds_since_1970 = your_date.strftime("%s")
UPDATE: OK, it's milliseconds, according to the documentation you can use your_date.strftime("%Q") to get the ms (but I've not tried yet).