Skip to content

Instantly share code, notes, and snippets.

@gingerlime
Last active September 16, 2019 03:08
Show Gist options
  • Star 2 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save gingerlime/757c7b4778c1ab68605dfce66ceb8378 to your computer and use it in GitHub Desktop.
Save gingerlime/757c7b4778c1ab68605dfce66ceb8378 to your computer and use it in GitHub Desktop.
Just an example of simple JSON parsing with/without JMESPath
// JSON webhook
[
{
"msys" => {
"message_event" => {
"type" => "spam_complaint",
"rcpt_to" => "user@example.com"
}
}
},
{ ... }
]
# 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)
# 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']
}
@styfle
Copy link

styfle commented Feb 17, 2018

Is this the JavaScript equivalent?

spam_complaint_emails = arr.filter(o => o.msys.message_event.type=='spam_complaint')

@kbenson
Copy link

kbenson commented Feb 17, 2018

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