-
-
Save gingerlime/757c7b4778c1ab68605dfce66ceb8378 to your computer and use it in GitHub Desktop.
Just an example of simple JSON parsing with/without JMESPath
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// JSON webhook | |
[ | |
{ | |
"msys" => { | |
"message_event" => { | |
"type" => "spam_complaint", | |
"rcpt_to" => "user@example.com" | |
} | |
} | |
}, | |
{ ... } | |
] |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# getting all email addresses for events with type "spam_complaint" | |
# with JMESPath | |
jmespath_query = "[].msys.message_event | [?type=='spam_complaint'].rcpt_to" | |
spam_complaint_emails = JMESPath.search(jmespath_query, payload) |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# getting all email addresses for events with type "spam_complaint" | |
# without JMESPath | |
spam_complaint_emails = payload | |
.map { |el| | |
el['msys'] | |
}.select { |el| | |
el.fetch('message_event', {}).fetch('type', nil) == 'spam_complaint' | |
}.map { |el| | |
el['message_event']['rcpt_to'] | |
} |
Well, given
var arr = [
{
"msys" : {
"message_event" : {
"type" : "spam_complaint",
"rcpt_to" : "user@example.com"
}
}
}
]
I think the equivalent in JavaScript would be
spam_complaint_emails = arr.map(item => item.msys.message_event)
.filter(me => me.type=='spam_complaint')
.map(me => me.rcpt_to);
or
spam_complaint_emails = arr.filter(item => item
.msys.message_event.type=='spam_complaint')
.map(item=>item.msys.message_event.rcpt_to);
Which path you choose as better is likely to depend on where additional attributes from the might be desired later.
Given I would probably do the same thing in Perl with maps and gresp, and I understand Ruby has all those same mechanisms, I'm not sure why the overly complex Ruby code, unless Ruby throws an error on invalid hash access?. In Perl I would just turn autovivification off and get eh undef (nil) as expected which evals to false for the grep.
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Is this the JavaScript equivalent?