How to preserve order in XML Array to Hash conversion?
I am trying to parse XML in Ruby using Nori, which Nokogiri uses internally. XML repeats multiple tags and the library parses duplicate tags as arrays and non-duplicate tags as normal elements (Hash)
<nodes>
<foo>
<name>a</name>
</foo>
<bar>
<name>b</name>
</bar>
<baz>
<name>c</name>
</baz>
<foo>
<name>d</name>
</foo>
<bar>
<name>e</name>
</bar>
</nodes>
analyzed as
{nodes: {
foo: [{name: "a"}, {name: "d"}],
bar: [{name: "b"}, {name: "e"}],
baz: {name: "c"}
}}
How do I preserve the order of the elements in the resulting hash like the result below?
{nodes: [
{foo: {name: "a"}},
{bar: {name: "b"}},
{baz: {name: "c"}},
{foo: {name: "d"}},
{bar: {name: "e"}},
]}
(This might be a library related question. But the goal is to know if anyone has encountered a similar problem and how to properly disassemble it)
+3
Sathish
source
to share
1 answer
Nori cannot do this on her own. What you can do is customize the Nori output like this:
input = {nodes: {
foo: [{name: "a"}, {name: "d"}],
bar: [{name: "b"}, {name: "e"}],
baz: {name: "c"}
}}
def unfurl(hash)
out=[]
hash.each_pair{|k,v|
case v
when Array
v.each{|item|
out << {k => item}
}
else
out << {k => v}
end
}
return out
end
output = {:nodes => unfurl(input[:nodes])}
puts output.inspect
This outputs the result that the original request was requested, which is different from the XML order:
{nodes: [
{foo: {name: "a"}},
{foo: {name: "d"}},
{bar: {name: "b"}},
{bar: {name: "e"}},
{baz: {name: "c"}},
]}
+1
joelparkerhenderson
source
to share