Let's say I had the string
"[1,2,[3,4,[5,6]],7]"
How would I parse that into the array
[1,2,[3,4,[5,6]],7]
?
Nesting structures and patterns are completely arbitrary in my usage case.
My current ad-hoc solution involves adding a space after every period and using YAML.load
, but I'd like to have a cleaner one if possible.
(One that does not require external libraries if possible)
That particular example is being parsed correctly using
JSON
:If that doesn't work, you can try running the string through
eval
, but you have to ensure that no actual ruby code has been passed, aseval
could be used as injection vulnerability.Edit: Here is a simple recursive, regex based parser, no validation, not tested, not for production use etc:
"Obviously" the best solution is to write your own parser. [ If you like writing parsers, have never done it before and want to learn something new, or want control over the exact grammar ]
Parslet transforms will match a single value as "simple" but if that value returns an array, you soon get arrays of arrays, then you have to start using subtree. returning objects however are fine as they represent a single value when transforming the layer above... so sequence will match fine.
Couple the trouble with returning bare arrays, with the problem that Array([x]) and Array(x) give you the same thing... and you get very confusing results.
To avoid this I made a helper class called Arr which represents an array of items. I could then dictate what I pass into it. Then I can get the parser to keep all the brackets even if you have the example that @MateuszFryc called out :) (thanks @MateuszFryc)
Use eval
The same can be done using Ruby standard libaray
YAML
as below :