Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Bring order to json #55

Merged
merged 2 commits into from
Oct 18, 2023
Merged
Show file tree
Hide file tree
Changes from 1 commit
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
6 changes: 3 additions & 3 deletions lib/dachsfisch/json2_xml_converter.rb
Original file line number Diff line number Diff line change
Expand Up @@ -23,8 +23,8 @@ def execute
def add_element(xml, element)
return unless element.is_a? Hash

element.each do |key, value|
add_node(xml, key, value) unless key.start_with?('@')
element['@@order']&.each do |key|
add_node(xml, key, element[key]) unless key.start_with?('@')
end
end

Expand All @@ -44,7 +44,7 @@ def add_node(xml, key, element)
end

def handle_attribute_and_namespaces(node, element)
element.keys.filter {|element_key| element_key.start_with?('@') }.each do |attribute_key|
element.keys.filter {|element_key| element_key.start_with?(/@[^@]/) }.each do |attribute_key|
if attribute_key.start_with? '@xmlns'
element[attribute_key].each do |namespace_key, namespace|
# add namespace of current scope to node. The root-ns($) gets 'xmlns' as key, named namespaces 'xmlns:name' respectively.
Expand Down
9 changes: 8 additions & 1 deletion lib/dachsfisch/xml2_json_converter.rb
Original file line number Diff line number Diff line change
Expand Up @@ -14,20 +14,27 @@ def execute
@fragment.elements.deconstruct.each do |root|
result[node_name(root)] = extract_node(root)
end
add_order_to_hash result
result.to_json
end

private

def add_order_to_hash(hash)
return if hash.keys.reject {|key| key.start_with?('@') }.empty?

hash['@@order'] = hash.keys.reject {|key| key.start_with?('@') }
end

def extract_node(node)
hash = {}
active_namespaces = add_namespaces_to_active_namespaces(node)
hash['@xmlns'] = active_namespaces unless active_namespaces.empty?

handle_attributes(hash, node)
node.children.each do |child|
handle_content(hash, child)
end
add_order_to_hash hash
hash
end

Expand Down
Loading