i have a json result:
0: { m_event_type_id: 0, m_event_log_description: "SYSTEM_LOG_44: RPM Reduction Due to High Wind Turbulence OFF", …}
1: { m_event_type_id: 0, m_event_log_description: "SYSTEM_LOG_44: RPM Reduction Due to High Wind Turbulence ON", …}
2: { m_event_type_id: 0, m_event_log_description: "Grease Pump Stopped 30 cycles executed", …}
3: { m_event_type_id: 0, m_event_log_description: "Grease Pump Started", …}
4: { m_event_type_id: 0, m_event_log_description: "SYSTEM_LOG_40: Battery Test Request Signal ON", …}
my result is stored in a variable call rslt,now i want to access
rslt.m_event_log_description
but it gives me error because cant access the property like this,any way to achive it?i dont want to write rslt[0].m_event_log_description because it just gives me the first one
You could use the Array#map function to extract a property from an object array as an array.
Try the following
someService.getData().subscribe(
response => {
this.rslt = response;
this.logDescriptions = response.map(item => item['m_event_log_description']);
},
error => {
// handle error
}
);
Now you could use the logDescriptions property in the template
<div *ngFor="description of logDescriptions">
{{ description }}
</div>
Related
I'm trying to convert an array of strings into an object for which each member uses the string for a key, and initializes the value to 0. (Classic accumulator for Word Count, right?)
Here's the style of the input data:
%dw 2.0
output application/dw
var hosts = [
"t.me",
"thewholeshebang.com",
"thegothicparty.com",
"windowdressing.com",
"thegothicparty.com"
]
To get the accumulator, I need a structure in this style:
var histogram_acc = {
"t.me" : 1,
"thewholeshebang.com" : 1,
"thegothicparty.com" : 2,
"windowdressing.com" : 1
}
My thought was that this is a slam-dunk case for reduce(), right?
So to get the de-duplicated list of hosts, we can use this phrase:
hosts distinctBy $
Happy so far. But now for me, it turns wicked.
I thought this might be the gold:
hosts distinctBy $ reduce (ep,acc={}) -> acc ++ {ep: 0}
But the problem is that this didn't work out so well. The first argument to the lambda for reduce() represents the iterating element, in this case the endpoint or address. The lambda appends the new object to the accumulator.
Well, that's how I hoped it would happen, but I got this instead:
{
ep: 0,
ep: 0,
ep: 0,
ep: 0
}
I kind of need it to do better than that.
As you said reduce is a good fit for this problem, alternatively you can use the "Dynamic elements" of objects feature to "flatten an array of objects into an object"
%dw 2.0
output application/dw
var hosts = [
"t.me",
"thewholeshebang.com",
"thegothicparty.com",
"windowdressing.com",
"thegothicparty.com"
]
---
{(
hosts
distinctBy $
map (ep) -> {"$ep": 0}
)}
See https://docs.mulesoft.com/mule-runtime/4.3/dataweave-types#dynamic_elements
Scenario 1:
The trick I think for this scenario is you need to enclose the expression for the distinctBy ... map with {}.
Example:
Input:
%dw 2.0
var hosts = [
"t.me",
"thewholeshebang.com",
"thegothicparty.com",
"windowdressing.com",
"thegothicparty.com"
]
output application/json
---
{ // This open bracket will do the trick.
(hosts distinctBy $ map {($):0})
} // See Scenario 2 if you remove or comment this pair bracket
Output:
{
"t.me": 0,
"thewholeshebang.com": 0,
"thegothicparty.com": 0,
"windowdressing.com": 0
}
Scenario 2: If you remove the {} from the expression {<expression distinctBy..map...} the output will be an Array.
Example:
Input:
%dw 2.0
var hosts = [
"t.me",
"thewholeshebang.com",
"thegothicparty.com",
"windowdressing.com",
"thegothicparty.com"
]
output application/json
---
//{ // This is now commented
(hosts distinctBy $ map {($):0})
//} // This is now commented
Output:
[
{
"t.me": 0
},
{
"thewholeshebang.com": 0
},
{
"thegothicparty.com": 0
},
{
"windowdressing.com": 0
}
]
Scenario 3: If you want to count the total duplicate per item, you can use the groupBy and sizeOf
Example:
Input:
%dw 2.0
var hosts = [
"t.me",
"thewholeshebang.com",
"thegothicparty.com",
"windowdressing.com",
"thegothicparty.com"
]
output application/json
---
hosts groupBy $ mapObject (value,key) -> {
(key): sizeOf(value)
}
Output:
{
"t.me": 1,
"thewholeshebang.com": 1,
"thegothicparty.com": 2,
"windowdressing.com": 1
}
Hilariously (but perhaps only to me) is the fact that I discovered the answer to this while I was writing my question. Hoping that someone will pose this same question, here is what I found.
In order to present the lambda argument in my example (ep) as the key in a structure, I must quote and intererpolate it.
"$ep"
Once I did that, it was a quick passage to:
hosts distinctBy $ reduce (ep,acc={}) -> acc ++ {"$ep": 0}
...and then of course this:
{
"t.me": 0,
"thewholeshebang.com": 0,
"thegothicparty.com": 0,
"windowdressing.com": 0
}
Currently, using API to collect JSON file. I have managed to extract this output as I demonstrated below.
And now I'm on the stage, that I have JSON extraction and need to make in the way that BQ will accept it. Without too much manipulation ( as this output potentially will be loaded on the daily bases.
{
"stats": [{
"date": "2018-06-17T00:00:00.000Z",
"scores": {
"my-followers": 8113,
"my-listed": 15,
"my-favourites": 5289,
"my-followings": 230,
"my-statuses": 3107
}
}, {
"date": "2018-06-18T00:00:00.000Z",
"scores": {
"my-statuses": 3107,
"my-followings": 230,
"my-lost-followings": 0,
"my-new-followers": 0,
"my-new-statuses": 0,
"my-listed": 15,
"my-lost-followers": 5,
"my-followers": 8108,
"my-favourites": 5288,
"my-new-followings": 0
}
}
.....
],
"uid": "123456789"
}
ANy help will be appreciated.
Currently I have this error:
Errors:
query: Invalid field name "my-new-followings". Fields must contain only letters, numbers, and underscores, start with a letter or underscore, and be at most 128 characters long. Table: link_t_perf_test1_b58d4465_3a31_40cb_987f_9fb2d1de29dc_source (error code: invalidQuery
Even when "my-new-followings" contain only integer (up to 5 digit) number.
I'm getting this string as query result from my database:
"%Sample.Struct{list: [], total: \"0.00\", day: 6, id: \"8vfts6\"}"
Is there any way to convert this one back to map?
I'm getting this error decoding it with poison
** (Poison.SyntaxError) Unexpected token: %
(poison) lib/poison/parser.ex:56: Poison.Parser.parse!/2
(poison) lib/poison.ex:83: Poison.decode!/2
I can't fix the way data is being added to database, i must find a proper way for a key/value route to easily retrive data from that. (this is just a sample for a more complex result)
As it was mentioned in comments, you should not use Code.eval_string. But, there is a way to safely convert your code to Elixir struct, using Code module:
ex(1)> encoded = "%Sample.Struct{list: [], total: \"0.00\", day: 6, id: \"8vfts6\"}"
"%Sample.Struct{list: [], total: \"0.00\", day: 6, id: \"8vfts6\"}"
First, get the AST from the string, but use the pattern matching to ensure it is a struct you are looking for ({:__aliases__, _, [:Sample, :Struct]}). All other (potentially malicious) code will fail this match:
iex(2)> {:ok, {:%, _, [{:__aliases__, _, [:Sample, :Struct]}, {:%{}, _, keymap}]} = ast} = Code.string_to_quoted(encoded)
{:ok,
{:%, [line: 1],
[{:__aliases__, [line: 1], [:Sample, :Struct]},
{:%{}, [line: 1], [list: [], total: "0.00", day: 6, id: "8vfts6"]}]}}
Here you have the full ast for you struct, and the keymap. You may now be tempted to use eval_quoted with the AST, to get the struct you needed:
iex(3)> {struct, _} = Code.eval_quoted(ast)
{%Sample.Struct{day: 6, id: "8vfts6", list: [], total: "0.00"}, []}
iex(4)> struct
%Sample.Struct{day: 6, id: "8vfts6", list: [], total: "0.00"}
But it is still not safe! Someone may put a function causing side effect into the string, like "%Sample.Struct{list: IO.puts \"Something\"}", which will be executed during the evaluation. So you will need to check the keymap firsts, if it contain safe data.
Or you may just use keymap directly, without evaluating anyting:
iex(5)> struct(Sample.Struct, keymap)
%Sample.Struct{day: 6, id: "8vfts6", list: [], total: "0.00"}
I am trying to use rest client in ruby to parse json but I am stuck how to validate the response (extract values from the response). Also I am trying to validate the valid response code(200) response.code does not work.
Following is the JSON response and Code that uses rest client to get it:
def self.call_legacy_transactions
get_response=RestClient::Request.execute(method: :get, url: 'URL', timeout: 15)
puts(get_response.body)
json_response = JSON.parse(get_response)
//Dont know how to get the values from response hash. Please suggest
end
JSON Response:
[
{
"value": "12345678912345",
"events": [
{
"transaction_id": 205,
"package_name": "",
"event_codes": [
465,
469,
471,
474,
410,
490,
1040
]
},
{
"transaction_id": 204,
"package_name": "",
"event_codes": [
465,
469,
474,
490
]
},
{
"transaction_id": 207,
"package_name": "",
"event_codes": [
465,
469,
471,
474,
490
]
}
]
}
]
I want the event code for each transaction for each value.
If you just want a flat list of event code integers, you can use:
json_response.flat_map do |value_data|
value_data[:events].flat_map do |event_data|
event_data[:event_codes]
end
end
UPDATE based on the comment "I want to extract event codes only where transaction id is 205":
If there could only ever be one item with that transaction ID:
json_response.flat_map do |value_data|
value_data[:events].find do |event_data|
event_data[:transaction_id] == 205
end[:event_codes]
end
If there could be many items with that transaction ID:
json_response.flat_map do |value_data|
value_data[:events].select do |event_data|
event_data[:transaction_id] == 205
end.flat_map do |event_data|
event_data[:event_codes]
end
end
You can call methods on the response to see the body, the response code, etc. More info in the README
Add to your code:
def self.call_legacy_transactions(tx_id = 205)
get_response=RestClient::Request.execute(method: :get, url: 'URL', timeout: 15)
puts(get_response.body)
# check if the response was successful
if get_response.code == 200
# need to parse the body
json_response = JSON.parse(get_response.body)
# the json response is an array of json objects
# we need to iterate over them and grab the value
# in the `events` key and iterate over those and
# select just the ones with the desired transaction id and
# get the value in each of the `event_codes` keys and
# then flatten all the sub arrays into one
event_codes = json_response.flat_map do |data|
data['events'].
select { |event| event['transaction_id'] == tx_id }.
flat_map { |event| event['event_codes'] }
end
event_codes # is now a list of just the event codes
end
end
With the above you can pass the transaction id into the method to get the event codes for any transaction e.g.
call_legacy_transactions 205
I am trying to delete an object from an array with Angularjs Resource:
CommandeDetail.delete({id:commandeDetail.id});
My factory :
.factory('CommandeDetail', function ($resource) {
return $resource('api/commandeDetail/:id', {}, {
'query': { method: 'GET', isArray: true},
'get': {
method: 'GET'
}
});
})
My object commandeDetail is (debug on Chrome before delete is called) :
commandeDetail: Resource
$$hashKey: "object:1136"
calibre: "douze"
categorie: "II"
certificatFournisseur: "AGROCERT"
commande: null
commandeId: 10
commentaire: null
dispJ4: 0
emballage: "COLIS 10 KG NET"
id: 35
marque: "ECOCERT"
max: 10
nbPalettes: 0
produit: "ABRICOT"
puht: 0
quantite: 10
tare: 0
valorisation: "Net"
The delete is well done on server side but I am getting this error on frontSide :
angular.js:11598 RangeError: Maximum call stack size exceeded
at join (native)
at Object.stringify (native)
at toJson (http://localhost:8080/bower_components/angular/angular.js:1048:15)
at defaults.defaults.transformRequest (http://localhost:8080/bower_components/angular/angular.js:8707:74)
at http://localhost:8080/bower_components/angular/angular.js:8655:12
at forEach (http://localhost:8080/bower_components/angular/angular.js:323:20)
at transformData (http://localhost:8080/bower_components/angular/angular.js:8654:3)
at $get.serverRequest (http://localhost:8080/bower_components/angular/angular.js:9319:23)
at processQueue (http://localhost:8080/bower_components/angular/angular.js:13175:27)
at http://localhost:8080/bower_components/angular/angular.js:13191:27
I don't know where that can come from. My object is quite simple.
If anybody can help me on this...
Thanks