Skip to content

Instantly share code, notes, and snippets.

@lukebyrne
Last active August 29, 2015 14:24
Show Gist options
  • Save lukebyrne/103f7a4b19c5e3a55f76 to your computer and use it in GitHub Desktop.
Save lukebyrne/103f7a4b19c5e3a55f76 to your computer and use it in GitHub Desktop.

I would like to sort the following JSON string:

'{"france":{"bordeaux":{"st emmilion":["gran crue"]},"burgundy":{"cote de nuits":{"chambolle musigny":["le musigny"]}}}}'

Into this output

region_one = [['France', 'france']] region_two = [['Bordeaux', 'bordeaux', class: 'france'], ['Burgundy', 'burgundy', class: 'france']] region_three = [['St Emmilion', 'st emmilion', class: 'bordeaux'], ['Cote De Nuits', 'cote de nuits', class: 'burgundy']] region_four = [['Gran Crue', 'gran crue', class: 'st emmilion'], ['Chambolle Musigny', 'chambolle musigny', class: 'cote de nuits']] region_five = [['Le Musigny', 'le musigny', class: 'chambolle musigny']]

require "json"
require "pp"
json = '{"australia":{"western australia":{"margeret river":["wollyabra"]},"south australia":["barossa"],"victoria":["yarra valley"],"new south wales":["hunter valley"],"queensland":[],"tasmania":[],"australian capital territory":[],"northern territory":[]},"france":{"bordeaux":{"st emmilion":["gran crue"]},"burgundy":{"cote de nuits":{"chambolle musigny":["le musigny"]}}}}'
regions = JSON.parse(json)
def partition_regions(regions, parent=nil, partitions=[], level=0)
partitions[level] ||= []
partion = partitions[level]
regions.each do |id, childs|
region = [id, id.capitalize]
region << {class: parent} if parent
partion << region
partition_regions(childs, id, partitions, level + 1) if childs
end
partitions
end
#pp regions
pp(*partition_regions(regions))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment