Lua: get POST data - lua

I'm receiving this JSON in the POST data:
{
"foo":{
"hi": "there",
"hello": "world"
}
}
In Lua, I want to get foo in order to save it in Redis, so it'd be great to save it as an string.
How can I get it?

You'll need to install json-lua or lua-cjson packages first. Then, parse the JSON response (received as string) and it gets converted to a table.
Using pairs() you can iterate over key-values of the table generated above.
OpenResty already bundles a fork of lua-cjson with it.

If the string is s, then this extracts the value of foo:
print(s:match('"foo"%s*:%s*(%b{})'))

Related

How to correctly return a list of dictionaries in Zapier Code (Python)?

The Zapier code documentation says that the output of a code zap can be either a dictionary or a list of dictionaries (See "Data Variable" section: https://zapier.com/help/code-python/).
When doing this,
output = [{'Booking':'Shirt'},{'Booking':'Jeans'}]
the output of the code returns only the first dictionary, however:
runtime_meta__duration_ms: 2
runtime_meta__memory_used_mb: 22
id: [redacted]
Booking: Shirt
Fields with no value:
runtime_meta__logs
What am I doing wrong here? Thanks a lot!
David from the Zapier platform team here. Code steps returning an array is a mostly undocumented (because there's no UI support and it's confusing, as you can tell) feature.
When testing, it'll only show the first item in the array. When it runs for real, all steps after the code step will run for each item in the array. The task history will reflect this
So set up the zap and turn on and it'll work like you expect.
Sorry for the confusion and let me know if you have any other questions!
For anyone still looking for an answer to this questions, below is what find out returning list in Zapier.
# first import and convert your input value to an array.
# special note any line items imported into a python variable are converted to list format.
my_items = input_data['my_CSV_string']
my_list_of_items = my_items.split(",")
# Create a new list array
my_new_list = []
length = len(my_list_of_items)
#Do all your computations
for i in range(length):
my_new_list.append(float(my_list_of_items[i])*1.5)
# After completing any tasks you can return the list as follows,
# If you are using line items keep the list in its original format
return {
'my_processed_values': my_new_list,
'original_values': my_list_of_items
}
# If you want to return it as a CSV "basically making the array flat"
my_old_CSV_list= ','.join(map(str, my_list_of_items))
my_new_CSV_list= ','.join(map(str, my_new_list))
return {
'my_processed_cvs_values': my_new_CSV_list,
'original_values': my_list_of_items
}
Hope this helps. I am not a Python expert but in theory the more lists used the longer the zap will take to process. Try to keep your python processing time to the lowest.
Best,

Array.size() returned wrong values (Grails)

I'm developing an app using Grails. I want to get length of array.
I got a wrong value. Here is my code,
def Medias = params.medias
println params.medias // I got [37, 40]
println params.medias.size() // I got 7 but it should be 2
What I did wrong ?
Thanks for help.
What is params.medias (where is it being set)?
If Grials is treating it as a string, then using size() will return the length of the string, rather than an array.
Does:
println params.medias.length
also return 7?
You can check what Grails thinks an object is by using the assert keyword.
If it is indeed a string, you can try the following code to convert it into an array:
def mediasArray = Eval.me(params.medias)
println mediasArray.size()
The downside of this is that Eval presents the possibility of unwanted code execution if the params.medias is provided by an end user, or can be maliciously modified outside of your compiled code.
A good snippet on the "evil (or lack thereof) of eval" is here if you're interested (not mine):
https://javascriptweblog.wordpress.com/2010/04/19/how-evil-is-eval/
I think 7 is result of length of the string : "[37,40]"
Seems your media variable is an array not a collection
Try : params.medias.length
Thanks to everyone. I've found my mistake
First of all, I sent an array from client and my params.medias returned null,so I converted it to string but it is a wrong way.
Finally, I sent and array from client as array and in the grails, I got a params by
params."medias[]"
List medias = params.list('medias')
Documentation: http://grails.github.io/grails-doc/latest/guide/single.html#typeConverters

rails decode json cyrrilic string

I have such string example, which i get from json (cp1251):
Ôèëüòð ìàñëÿíûé OPEL/GM/DAEWOO
which mean:
Фильтр масляный OPEL/GM/DAEWOO
this tool http://www.artlebedev.ru/tools/decoder/ say that i must use CP1252 → CP1251 decoder. I try it so:
my_string.force_encoding('cp1252').force_encoding('1251')
but it didn't solve my problem. What i do wrong?
how could i convert to normall view my json cyrrillic string in RoR?
i get json from url so:
jsonAE = JSON.load(open('http://******/portal.api?l=*****&p=Sih2*****&act=price_by_nr_firm&nr='+article_nr+'&oe=true'))
from json i get:
{"result":[{"nr":"OC90","brand":"Knecht","name":"Фильтр масляный OPEL/GM/DAEWOO","stock":"-","delivery":"не известно","minq":"1","upd":"16.03.15 23:40","price":"130.34","currency":"руб."},{"nr":"OC90","brand":"Knecht","name":‌​"Фильтр масляный OPEL/GM/DAEWOO","stock":"-","delivery":"не известно","minq":"1","upd":"17.03.15 00:05","price":"130.34","currency":"руб."}]}
but it turn's to something bad with JSON.load
▶ puts 'Ôèëüòð ìàñëÿíûé OPEL/GM/DAEWOO'
.encode(Encoding::CP1252)
.force_encoding(Encoding::CP1251)
.encode(Encoding::UTF_8)
#⇒ Фильтр масляный OPEL/GM/DAEWOO
The string in ruby is suspected to be utf8ed. So, the first action is to inform ruby that the string is actually in one-byte. Than we say “hey, don’t care, I know this one-byte is actually cyrillic.” And, finally, turn it back to utf-8.
Hope it helps.

Send params{} hash to another method in same controller

I am working on very complex and dynamic form where I do lot of calls to various methods to render partials depending upon values chosen for drop downs using jQuery. Problem is that after filling the form if it fails validation the form loses all the filled in values upon re-load. I got around this by sending some specific values from params{} hash to methods for my partials on re-load. But it is very cumbersome and I have large number of elements in params hash. How can send the whole params{} to another method in the same controller using jQuery?
Ok I tried this in my form:
$.post("/collections/show_selected_media_fields",{media_type: $("#collections_controller_ev0_media_id option:selected").text(), parent_form_action: "<%=params[:action]%>",ev0_manufacturer_id:"<%=params[:collections_controller_ev0].inspect%>", }, function(data) {$("#show_selected_media_fields").html(data);});
It produces following string sent as parameter:
Parameters: {"ev0_manufacturer_id"=>"{"client_asset_id"=>"", "status_id"=>"6", "server_
name"=>"", "media_id"=>"11", "serial_number"=>"", "evidence_number&quot
;=>"qwe", "notes"=>"", "model"=>"", "manufacturer_id"=>"69&quot
;, "interface"=>"SATA", "obtained_from"=>"wr", "evidence_type_id"=>"1"}
", "media_type"=>"Server", "parent_form_action"=>"quick_save"}
how can I convert this raw string to a hash in controller?
{"client_asset_id"=>
needs to be converted to
{"client_asset_id"=>"",... etc}
===========
ok I tried Tom's method. That produces the params as a string in the following shape. I tried to convert it into hash by doing an eval on it. But it errors out.
{commit=>Save, ev1_current_location_id=>, collections_controller_ev1=>{file_system=>NTFS, obtained_from=>, evidence_number=>, interface=>SAT
A, size_unit=>GB, manufacturer_id=>, encryption_version=>, media_id=>3, size=>, evidence_type_id=>3, other_encryption=>, encryption_method=>
N/A, serial_number=>, model=>, encryption_key=>}, ev0_from_location_category=>, ev0_obtained_from_email_id=>, collections_controller_ev0=>{o
btained_from=>, evidence_number=>, media_id=>1, evidence_type_id=>1, status_id=>6}, custody_action=>Create, collection=>{acquired_by=>Amande
ep Singh, custodian_id=>12, matter_id=>58, location=>sa Nose, client_id=>11, software_version=>, collection_date_time=>Fri Nov 30 14:28:06 -
0800 2012, acquisition_method=>Direct Collection, notes=>, software_id=>1}, _method=>put, utf8=>Γ£ô, ev1_current_location_category=>, ev0_cu
rrent_location_category=>, add_working_copy=>No, ev1_obtained_from_email_id=>, authenticity_token=>3vyn6057DDIyfgTnbckeh5heRTIgcVBfxtY89Krfr
/c=, ev1_existing_artifact_type=>, ev0_from_location_id=>, action=>quick_save, ev1_from_location_id=>, ev1_from_location_category=>, ev0_cur
rent_location_id=>, controller=>collections}
using .to_json and HTMLEntities gem I have gotten to a point where I have the following string. I need to convert it back to params hash. How to?
{"utf8"=>"Γ£ô","collection"=>{"acquired_by"=>"Amandeep Singh","notes"=>"","matter_id"=>"58","software_id"=>"1","acquisition_method"=>"Direct
Collection","client_id"=>"11","custodian_id"=>"0","collection_date_time"=>"Fri Nov 30 15=>52=>12 -0800 2012","software_version"=>"","locati
on"=>"sa Nose"},"ev0_current_location_id"=>"","ev1_existing_artifact_type"=>"","ev1_obtained_from_email_id"=>"","custody_action"=>"Create","
action"=>"quick_save","ev0_current_location_category"=>"","ev1_from_location_category"=>"","_method"=>"put","ev0_obtained_from_email_id"=>""
,"ev0_from_location_category"=>"","ev1_current_location_category"=>"","commit"=>"Save","controller"=>"collections","authenticity_token"=>"3v
yn6057DDIyfgTnbckeh5heRTIgcVBfxtY89Krfr/c=","ev0_from_location_id"=>"","ev1_current_location_id"=>"","collections_controller_ev0"=>{"status_
id"=>"6","media_id"=>"9","obtained_from"=>"","evidence_number"=>"","evidence_type_id"=>"1"},"collections_controller_ev1"=>{"media_id"=>"3","
encryption_key"=>"","encryption_version"=>"","size"=>"","obtained_from"=>"","encryption_method"=>"N/A","model"=>"","evidence_number"=>"","ev
idence_type_id"=>"3","size_unit"=>"GB","other_encryption"=>"","interface"=>"SATA","file_system"=>"NTFS","serial_number"=>"","manufacturer_id
"=>""},"ev1_from_location_id"=>"","add_working_copy"=>"No"}
========== edit==========
I am using the following in my view.
JSON( params[:collections_controller_ev0])
It sends following quoted string to my controller.
{"evidence_number":"","notes":"","size":"","model":"","evidence_type_id":"1","media_id":"1","obtained_from":"","status_id":"6","manufacturer_id":"","size_unit":"GB"}
I convert it into valid JSON string as below using gsub('"','"'). The output is a VALID JSON string as validated by http://jsonlint.com/ shown below.
{"evidence_number":"","notes":"123","size":"123","model":"123","evidence_type_id":"1","media_id":"1","obtained_from":"","status_id":"6","manufacturer_id":"69","size_unit":"GB"}
JSON.parse works without error on this string but does not produce a properly formed hash. It produces following:
notes123evidence_numbersize123model123evidence_type_id1media_id1obtained_fromstatus_id6size_unitGBmanufacturer_id69
Can someone please tell me how to correct this?
Try <%=raw params[:action]%> and <%=raw params[:collections_controller_ev0]%> instead
I think it will work fine.
$.post("/collections/show_selected_media_fields",{media_type: $("#collections_controller_ev0_media_id option:selected").text(), parent_form_action: <%=raw params[:action]%>,ev0_manufacturer_id:<%=raw params[:collections_controller_ev0].inspect%>, }, function(data) {$("#show_selected_media_fields").html(data);});
params is basically a hash. So you can use .to_json on it. Then in your controller you can convert it from JSON to a hash with JSON.parse().
It's generally a much better idea to use JSON if you're going to be dealing with it in Javascript or HTML at all.
The method showed in my last edit works! it produces correct hash.

Can't turn array into a string error

I have a simple call
JSON.parse(Panda.get("/videos/#{self.panda_video_id}/encodings.json"))
Which returns :
can't convert Array into String
This is because the Panda.get("/videos/#(self.panda_video_id}/encodings.json") call returns an array in the new Panda 1.0.0 gem.
I also tried :
JSON.parse(Panda.get("/videos/#{self.panda_video_id}/encodings.json").to_s)
This returns:
705: unexpected token at 'created_at2010/07/19 20:28:13 +0000video_id4df3be7b6c6888ae86f7756c77c92d8bupdated_at2010/07/19 20:28:30 +0000started_encoding_at2010/07/19 20:28:21 +0000id6e2b35ad7d1ad9c9368b473b8acd0abcextname.mp4encoding_time0encoding_progress100file_size513300height110statussuccesswidth200profile_idf1eb0fe2406d3fa3530eb7324f410789'
Question
How would you turn the call at the top so that it returns a string?
does the following work:
panda_data = Panda.get("/videos/#{self.panda_video_id}/encodings.json")
JSON.parse(panda_data.to_s)
if it doesn't what is the error output?
If panda_data is an array, panda_data.to_s is guaranteed to return a string
Not that anyone had a chance at this, but
Panda_Gem since -v=0.6 has made all Panda.[get, post, etc.] requests return a hash. So you don't need the JSON.parse anymore. Removing the JSON.parse allows it to work.

Resources