I have a simple question :
Using node-red, I have a result in this format: [{}], but I want it like this {}.
Could you please help me?
Thanks in advance.
[{...}] is an array containing an object. {...} is an object. To go from [{}] to {}, simply index the first element like so:
result = [{"stuff": "things", ...}];
new_result = result[0];
new_result is {"stuff": "things", ...}
You can use the change node to extract the first element from an array using JSONATA.
[2
e.g.
[{"id":"efe073293d865f28","type":"inject","z":"d8cb24f4281c772e","name":"","props":[{"p":"payload"},{"p":"topic","vt":"str"}],"repeat":"","crontab":"","once":false,"onceDelay":0.1,"topic":"","payload":"[{\"id\":1,\"foo\":\"bar\"}]","payloadType":"json","x":190,"y":120,"wires":[["2f3f75244999adeb"]]},{"id":"2f3f75244999adeb","type":"change","z":"d8cb24f4281c772e","name":"","rules":[{"t":"set","p":"payload","pt":"msg","to":"payload[0]","tot":"jsonata"}],"action":"","property":"","from":"","to":"","reg":false,"x":440,"y":120,"wires":[["78bf1271407b0e82"]]},{"id":"78bf1271407b0e82","type":"debug","z":"d8cb24f4281c772e","name":"","active":true,"tosidebar":true,"console":false,"tostatus":false,"complete":"false","statusVal":"","statusType":"auto","x":690,"y":120,"wires":[]}]
Related
I am receiving params like this "[[201], [511], [3451]]", I want to convert it into [201, 511, 3451]
Let's say params is what you're receiving, you can use scan and map to use a Regular Expression, look for the digits in the response and then map each item in the array to an integer:
params = "[[201], [511], [3451]]"
params_array = params.scan(/\d+/).map(&:to_i)
What we are doing here is we are looking through the string and selecting only the digits with the Scan method, afterwards we get a string array so to convert it into integers we use the Map method. As per the map method, thanks to Cary Swoveland for the update on it.
It will help you!
str_arr = "[[201], [511], [3451]]"
JSON.parse(str_arr).flatten
or
eval(str_arr).flatten
here is an interesting way (note that it only works in case your params is an array string)
arr1 = instance_eval("[1,2,3]")
puts arr1.inspect # [1,2,3]
arr2 = instance_eval("[[201], [511], [3451]]")
puts arr2.inspect # [[201], [511], [3451]]
First, I would make a sanity check that you don't get malevolent code injected:
raise "Can not convert #{params}" if /[^\[\]\d]/ =~ params
Now you can assert that your string is safe:
params.untaint
and then convert
arr = eval(params).flatten
or
arr = eval(params).flatten(1)
depending on what exactly you want to receive if you have deeply-nested "arrays" in your string.
I have an array
result = [{:cluster=>[0, 4], :id=>1, :units=>346, :num1=>0.161930681e7, :num2=>0.14223512616e9, "description"=>"Foo"}, { ...
And I want to take out any objects with number of units equal to 0. Looking for something similar to array.splice() but for Ruby
What is the best way to do this ?
You can use the #reject method to return the array without objects whose :units equals 0:
result.reject { |hash| hash[:units] == 0 }
There's also #reject! and #delete_if, which can be used in the same way as above but both modify the array in place.
Hope this helps!
You can achieve the same result using select method implemented on the Array class:
result.select { |el| el[:units] == 0 }
There is an array like this:
a = [1,2,3,4]
I want to get the return values of size and sum like this.
size = a.size
sum = a.sum
Is there a way to get both values by a one-liner like this?
size, sum = a.some_method(&:size, &:sum)
In Ruby, you can do multiple assignments in one line:
size, sum = a.size, a.sum
It doesn't make it more readable, though.
You could do this:
a = [1,2,3,4]
methods = [:size, :max, :min, :first, :last]
methods.map { |m| a.send m }
#=> [4, 4, 1, 1, 4]
Another possible solution:
size, sum = a.size, a.reduce { |a,b| a = a + b }
Previous answers are correct, but if OP was actually concerned about walking the array multiple times, then array.size does not walk the array, it merely returns the length, thus there is no saving from a oneliner in that regard.
On the other hand, if size was just an example and the question is more about making multiple operations on an array in one go, then try something like this:
arr = [1,2,3,4,5,6]
product,sum = arr.inject([1,0]){|sums,el| [sums[0]*el, sums[1]+el]}
# => [720, 21]
That is, inject the array with multiple initial values for the results and then calculate new value for every element.
I am trying to iterate over a list of parameters, in a grails controller. when I have a list, longer than one element, like this:
[D4L2DYJlSw, 8OXQWKDDvX]
the following code works fine:
def recipientId = params.email
recipientId.each { test->
System.print(test + "\n")
}
The output being:
A4L2DYJlSw
8OXQWKDDvX
But, if the list only has one item, the output is not the only item, but each letter in the list. for example, if my params list is :
A4L2DYJlSwD
using the same code as above, the output becomes:
A
4
L
2
D
Y
J
l
S
w
can anyone tell me what's going on and what I am doing wrong?
thanks
jason
I run at the same problem a while ago! My solution for that it was
def gameId = params.gameId
def selectedGameList = gameId.class.isArray() ? Game.getAll(gameId as List) : Game.get(gameId);
because in my case I was getting 1 or more game Ids as parameters!
What you can do is the same:
def recipientId = params.email
if(recipientId.class.isArray()){
// smtg
}else{
// smtg
}
Because what is happening here is, as soon as you call '.each' groovy transform that object in a list! and 'String AS LIST' in groovy means char_array of that string!
My guess would be (from what I've seen with groovy elsewhere) is that it is trying to figure out what the type for recipientId should be since you haven't given it one (and it's thus dynamic).
In your first example, groovy decided what got passed to the .each{} closure was a List<String>. The second example, as there is only one String, groovy decides the type should be String and .each{} knows how to iterate over a String too - it just converts it to a char[].
You could simply make recipientId a List<String> I think in this case.
You can also try like this:
def recipientId = params.email instanceof List ? params.email : [params.email]
recipientId.each { test-> System.print(test + "\n") }
It will handle both the cases ..
Grails provides a built-in way to guarantee that a specific parameter is a list, even when only one was submitted. This is actually the preferred way to get a list of items when the number of items may be 0, 1, or more:
def recipientId = params.list("email")
recipientId.each { test->
System.print(test + "\n")
}
The params object will wrap a single item as a list, or return the list if there is more than one.
In lua ,im calling a function which returns a table variable that contains many parameter internally..but when i get that value i couldnt access the paramter which is present in the table. I can see the tables parameter in the original function in the form of
[[table:0x0989]]
{
[[table:0x23456]]
str = "hello"
width = 180
},
[[table:0x23489]]
{
str1 = "world"
}
it shows like this.but when it returns once i can able to get the top address of table like [[table:0x0989]]..when i tried acessing the tables which is present inside the main table.it is showing a nil value...how do i call that ?? can anyone help me??
If I'm reading it correctly you're doing this:
function my_function ()
--do something
return ({a=1, b=2, c=3})
end
From that you should be able to do this:
my_table = my_function()
then
print(my_table.a) --=> 1
print(my_table.b) --=> 2
print(my_table.c) --=> 3