0

I use Xpath to get some elements of an XML. Is there a similar way to obtain it for an object/hash?

I need get the value of a JSON object using some kind of selectors, which would need to be flexible enough because this JSON won't always be structured the same way.

Something like this is xpath would have been //data/children/*/title for instance.

Is there something similar for objects? I don't want to convert my object to an XML, it would bring other problems.

Adriaan
  • 17,741
  • 7
  • 42
  • 75
gordie
  • 1,637
  • 3
  • 21
  • 41
  • Possible duplicate of https://stackoverflow.com/questions/8481380/is-there-a-json-equivalent-of-xquery-xpath. There are multiple tools but none with the clout of xpath or css selectors. – max Mar 13 '20 at 11:26
  • If this is on the backend (e.g. ruby has access to the `JSON`) then you can convert it to a `Hash` and add `hashie` as a dependency this gem offers deep traversal methods for a hash object including `deep_fetch`, `deep_find` and `deep_locate` https://github.com/hashie/hashie#deepfetch – engineersmnky Mar 13 '20 at 13:04

1 Answers1

0

Ruby 2.7 introduced pattern matching, which might solve your problem. For example:

data = {
  data: {
    children: [
      {
        title: 'Find me'
      },
      {
        title: 'I am wrong'
      }
    ]
  }
}

case data
  in {data: {children: [{title: 'Find me'}, *rest]}}
  puts 'found'
else
  puts 'not found'
end

In this case, Ruby checks the data structure and prints 'ok' if {title: 'Find me'} is in children key.

Masafumi Okura
  • 694
  • 3
  • 12